I have created a function to analyze a text in a file according to some rules.
void parse(const char *fileName){
ifstream f;
f.open("test.txt");
char ch;
string str = "";
while(!f.eof()){
f.get(ch);
if(isspace(ch)){
cout << ch << " -> Space." << endl;
} else if(ch == '/'){
cout << ch << " -> Symble." << endl;
} else if(isalpha(ch)){
str = ch;
f.get(ch);
while(isalnum(ch)){
str += ch;
f.get(ch);
}
f.putback(ch);
cout << str << " -> String." << endl;
} else if(isdigit(ch)){
str = ch;
f.get(ch);
while(isdigit(ch)){
str += ch;
f.get(ch);
}
f.putback(ch);
cout << str << " -> Number." << endl;
} else {
cout << ch << " -> Wrong value." << endl;
}
}
f.close();
}
// The implementation
int main(){
parse("test.txt");
return 0;
}
The content of test.txt
for example:
Lion King 200 26/12/1910
After searching for the problem I found when reaching the last character it is repeated continuously and does not reach the end of the file.
Debugging window:
The result:
How to make the function to reach the end of file?
(+) A way to solve the problem but not the best.
I have solved the problem but using a bad way in my opinion, I've put a condition in several places to know if I have reached the end of file. if(f.eof()) break;
void parse(const char *fileName){
ifstream f;
f.open("test.txt");
char ch;
string str = "";
while(!f.eof()){
f.get(ch);
if(isspace(ch)){
if(f.eof()) break;
cout << ch << " -> Space." << endl;
} else if(ch == '/'){
if(f.eof()) break;
cout << ch << " -> Symble." << endl;
} else if(isalpha(ch)){
str = ch;
f.get(ch);
while(isalnum(ch)){
str += ch;
f.get(ch);
if(f.eof()) break;
}
cout << str << " -> String." << endl;
if(f.eof()) break;
f.putback(ch);
} else if(isdigit(ch)){
str = ch;
f.get(ch);
while(isdigit(ch)){
str += ch;
f.get(ch);
if(f.eof()) break;
}
cout << str << " -> Number." << endl;
if(f.eof()) break;
f.putback(ch);
} else {
if(f.eof()) break;
cout << ch << " -> Wrong value." << endl;
}
}
f.close();
}
Is there another good way instead that?