I am facing a problem with C++ and C, where my ifstream object, or file pointer is not reading a text file properly, and displays illegal characters when output. However, when I read a .dat file, it outputs the correct result.
This is the C code:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
void main() {
FILE *file;
char ch;
file = fopen("code.dat", "r");
while((ch = getc(file)) != EOF)
printf("%c", ch);
getch();
fclose(file);
}
This is the CPP code:
#include <fstream.h>
#include <iostream.h>
#include <conio.h>
#include <string.h>
int main() {
clrscr();
fstream file;
file.open("code.dat", ios::in);
char ch, c;
char token[6];
int id = 0, op = 0, key = 0;
while (!file.eof()) {
file >> ch;
if(ch == ' ') {
if ((ch > 64 && ch < 91) || (ch > 96 && ch < 123))
id += 1;
}
}
cout << id;
file.close();
getch();
return 0;
}