c++ -读取文件字符时的无限循环
C++ - infinite loop when reading characters of file
我想从文件中读取一些值并返回它们的代码。例如,如果我在文件中有"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;
}
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 当想要以类似的字符终止时,获得无限循环在C 中
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 为什么我的程序在输入字符时有一个无限循环
- 无限 while 循环 - 字符关闭不起作用C++
- c++ -读取文件字符时的无限循环
- 输入字符时的无限循环
- 当用户输入一个字符而不是浮点和整数时,如何避免无限循环
- 为什么这会导致字符而不是双精度的无限循环