ifstream无限循环(它似乎永远找不到停止读取的标记)
一个相当简单的问题...我不明白为什么这个循环永远不会结束...
#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 获取故障位字符的情况吗?
A rather quick question... I can't figure out why this loop never ends...
#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;
}
The input file
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
The output:
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
Is this a case of peek getting a failbit character?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
peek 让您看到下一个字符,我认为在本例中是距离值之后的换行符。因为它不是 Q,所以循环尝试读取另外三个整数值,失败并设置错误位。 peek,当失败时,返回 EOF - 所以你永远看不到 Q。
peek lets you see the next character, which I think in this case is the newline after the distance value. since it's not Q, the loop tries to read another three integer values, fails, and sets the error bit. peek, when there's a failure, returns EOF - so you never get to see the Q.
在开始读取文件之前请尝试以下操作。
它将导致诸如换行符之类的空白被忽略。
Try the following before starting to read from the file.
It will cause whitespace such as line break to be ignored.