[英]File not reading properly C++ ifstream
我有一个使用ifstream读取文件的应用程序。 每行文件中有1000个数字。 我的应用程序应阅读所有这些行。
但是,当我的行数少于800时,它将计数显示为0,这是为什么呢? 代码如下。
int tmp, count=0,ucount=0;
ifstream fin("rnum.txt");
while(fin >> tmp)
{
count++;
}
cout<<"showing count: "<<count<<endl;
ucount=count;
fin.open("rnum.txt");
int i=0;
cout<<"Before entering loop"<<count<<endl;
while(fin >> tmp){
iArray[i++]=tmp;
}
当我读取1000行的文件时,它也只读取720行。 我不明白为什么会这样读。
代码有什么问题吗?
我的要求是将COUNT行数添加到ucount变量中。
要计算文件中的行数,请使用getline
函数。
#include<string>
std::string line;
while (std::getline(fin, line))
{
++count;
}
这不会解决您的错误,因为我认为这与输入文件本身有关,但是一次读取文件至少可以使其更快:
vector<int> iArray;
int tmp;
ifstream fin("rnum.txt");
while (fin >> tmp)
{
iArray.push_back(tmp);
}
cout << "showing count: " << iArray.size() << endl;
您需要在第二次打开文件之前使用fin.close()
关闭文件,或者保持文件打开,重置读取指针并清除eof标志。
如果输入不正确(如果遇到字符而不是数字),>>操作将失败,并且fin >> tmp
返回false,从而过早中断循环。
此外,您应该在重新打开文件之前将其关闭。 我相信您需要/想要的功能仅仅是fin.seekg(0)
。
此外,您的代码可以简化为:
int temp;
ifstream fin("rnum.txt");
vector<int> iArray;
while(fin >> tmp)
{
iArray.push_back(tmp);
}
std::cout << "showing count : " << iArray.size();
如@trojanfoe在https://stackoverflow.com/a/16058205/6459731中所建议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.