此函数用于打开一个.txt文件,如下所示:
1 4 5
2 4 6等(数字之间带制表符)
并将每个数字保存在一个变量中
void Graph::readData(char* fname)
{
//cout<<"1";
int x,y,w;//assistant variables
ifstream input;//stream for reading file
input.open(fname,ios::in);
if(!input)
{
cerr<<"Input file doesn't exist"<<endl;//error if file doens exist
}
else
{
cout<<"Input file opened"<<endl;
cout<<"Reading Data from file..."<<endl;
while(!input.eof())//till the end of file
{
input>>x>>y>>w;//reads the links-site
cout<<"x: "<<x<<"y:"<<y<<"w: "<<w<<endl;
insertLink(x,y,w);//inserts them
}
input.close();//closing file
}
}然而,当我"cout“结果时,我得到的结果如下:
x=1 y= w=5
x=2 y= w=6没有y!
为什么会发生这种情况呢?
PS:此外,eof()在文件结束后变为true (多读一行)。如何在迭代过程中正确停止?
这是我尝试读取的文件:http://www.speedyshare.com/tpvuD/input.txt
发布于 2014-02-15 00:43:53
要正确停止迭代,请将循环编写为:
while(input>>x>>y>>w)//till the end of file
{ /* ... */ }请勿选中input.eof()。
https://stackoverflow.com/questions/21784795
复制相似问题