C++ - 读取文件字符时的无限循环
问题描述:
我想从文件中读取一些值并返回它们的代码。例如,如果我有“如果(X = 3)”的文件中,则输出将是这样的:C++ - 读取文件字符时的无限循环
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);
}
,这里是扫描功能
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福nction。
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;
}
是有考虑所有的模式,但我没有复制他们,因为岗位没有得到过久 – Payf1
不要在'SCAN'功能打开文件:它将从每次启动时读取。您需要在解析之前将其打开,并引用流到各种函数的流。 –
有没有办法做到这一点,而无需更改主程序? – Payf1