Reputation: 375
I want to read some values from the file and return their codes. for example if I have "if(x=3)" in the file, the output would be something like this:
22 if
12 (
2 x
11 =
1 3
13 )
each number in the left is a code for the value in right side for example for identifier (here is X) it is 2 and so on.
The problem is that when I open the "test.txt" file in the function SCAN and it found the Code then it return it and put the equivalent character to be shown at the output. but from then it goes to infinite loop because the previous returned characters can not be changed. So it returned infinite output of "22 if".
int main () {
int Code;
string Str;
do
{
Code=SCAN(Str);
cout<<Code<<"\t"<<Str<< endl;
}
while(Code !=0);
}
and here is the SCAN function
int SCAN(string& String){
int Code;
ifstream ifs;
ifs.open ("test.txt", ifstream::in);
char c = ifs.get();
String=c;
while (ifs.good()) {
if (isspace(c)){
c = ifs.get();
}
if (isalpha(c)){
string temp;
while(isalpha(c)){
temp.push_back(c);
c = ifs.get();
}
String = temp;
return 2;
}
if(isdigit(c)){
string temp;
while(isdigit(c)){
temp.push_back(c);
c = ifs.get();
}
String=temp;
return 1;
}
if(c=='('){
c = ifs.get();
return 12;
}
c = ifs.get();
}//endwhile
ifs.close();
return 0;
}
I have posted summary of my code to be easy to read which contains the loop for alphabets digits spaces (just ignores the spaces) and "(".
Upvotes: 3
Views: 275
Reputation: 3180
I do want to solve this problem but I wanted to know if there is any way to fix it without changing the main function. I mean by modifying just the SCAN function.
bool isOpened = false;
ifstream ifs;
int SCAN(string& String){
int Code;
if (!isOpened) {
ifs.open ("test.txt", ifstream::in);
isOpened = true;
}
...
ifs.close();
isOpened = false;
return 0;
}
Upvotes: 1