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

标签 c++ function file infinite-loop

我想从文件中读取一些值并返回它们的代码。例如,如果我在文件中有“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/

相关文章:

c++ - 来自 boost Asio deadline_timer 的多个 async_wait

c - 如何在c中定义常用函数

c# - 无法在多线程中访问文件

c++ - Boost rng vs OpenCV rng vs c++11 std::random?

c++ - Unordered_set迭代器随机

spring-boot - 在 Controller 中传递服务的功能,以便不复制 try catch block

javascript - ES6解构函数参数——命名根对象

linux - 通过在 bash 中附加来有条件地合并文件

.net - 如何使用 FileStream 读取超过 2 GB 的大文件

c++ - 用新的集合对象替换集合对象