C++ - 读取文件字符时无限循环
C++ - infinite loop when reading characters of file
我想从文件中读取一些值和 return 它们的代码。例如,如果我在文件中有 "if(x=3)",输出将是这样的:
22 if
12 (
2 x
11 =
1 3
13 )
左边的每个数字都是右边值的代码,例如标识符(这里是 X)是 2 等等。
问题是,当我在 SCAN 函数中打开 "test.txt" 文件时,它找到了代码,然后它 return 并将等效字符显示在输出中。但从那时起它进入无限循环,因为之前的 returned 字符无法更改。所以它return编辑了“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;
}
我想从文件中读取一些值和 return 它们的代码。例如,如果我在文件中有 "if(x=3)",输出将是这样的:
22 if
12 (
2 x
11 =
1 3
13 )
左边的每个数字都是右边值的代码,例如标识符(这里是 X)是 2 等等。
问题是,当我在 SCAN 函数中打开 "test.txt" 文件时,它找到了代码,然后它 return 并将等效字符显示在输出中。但从那时起它进入无限循环,因为之前的 returned 字符无法更改。所以它return编辑了“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;
}