一个相当简单的问题...我不明白为什么这个循环永远不会结束...
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//[city1][city2][distance]
ifstream sourcefile;
int data[50][50];
sourcefile.open("a5.txt");
if(!sourcefile)
{
cout << "file not found" << endl;
return 1;
}
int temp1, temp2, temp3, check;
char reader;
check = 0;
while(reader != 'Q')
{
sourcefile >> temp1;
sourcefile >> temp2;
sourcefile >> temp3;
data[temp1][temp2] = temp3;
cout << "data[" << temp1 << "][" << temp2 << "] = " << temp3 << endl;
check++;
if(check > 100)
{
cout << "overflow" << endl;
return 1;
}
reader = sourcefile.peek();
}
return 0;
}
输入文件
1 2 10
1 4 30
1 5 99
2 3 50
2 1 70
3 5 10
3 1 50
4 3 20
4 5 60
5 2 40
Q
输出:
data[1][2] = 10
data[1][4] = 30
data[1][5] = 99
data[2][3] = 50
data[2][1] = 70
data[3][5] = 10
data[3][1] = 50
data[4][3] = 20
data[4][5] = 60
data[5][2] = 40
data[0][2] = 40
data[0][2] = 40
...
... (repeats "data[0][2] = 40" about 60 more times)
overflow
这是 peek 获取失败位字符的情况吗?
最佳答案
peek 让您看到下一个字符,我认为在本例中是距离值之后的换行符。因为它不是 Q,所以循环尝试读取另外三个整数值,失败并设置错误位。 peek,当失败时,返回 EOF - 所以你永远看不到 Q。
关于c++ - ifstream无限循环(它似乎永远找不到停止读取的标记),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4293759/