c++ -读取文件字符时的无限循环

C++ - infinite loop when reading characters of file

本文关键字:无限循环 字符 文件 读取 c++      更新时间:2023-10-16

我想从文件中读取一些值并返回它们的代码。例如,如果我在文件中有"if(x=3)",输出将是这样的:

22 if 12 ( 2 x 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);
}

这是SCAN函数

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;
}

我已经发布了我的代码摘要,以方便阅读,其中包含循环字母,数字,空格(只是忽略空格)和"("。

我确实想解决这个问题,但我想知道是否有在不改变主要功能的情况下修复它的方法。我是说通过修改只有SCAN功能

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;
}