我想从文件中读取一些值并返回它们的代码。例如,如果我在文件中有“if(x=3)”,输出将是这样的:
22 如果
12 (
2×
11 =
1 3
13)
左边的每个数字都是右边值的代码,例如标识符(这里是 X)是 2 等等。
问题是,当我在 SCAN 函数中打开“test.txt”文件时,它找到了代码,然后返回它并将等效字符显示在输出中。但从那时起它进入无限循环,因为无法更改先前返回的字符。所以它返回无限输出“22 if”。
int main () {
int Code;
string Str;
do
{
Code=SCAN(Str);
cout<<Code<<"\t"<<Str<< endl;
}
while(Code !=0);
}
这是扫描函数
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 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;
}
关于C++ - 读取文件字符时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32939369/