我正在创建一个程序(在 C++ 中),该程序采用 ASCII 文件并从每一行读取一些值,直到到达文件末尾。我在用ifstream
读取文件,当我使用ifstream.eof()
方法。然而,这一次,即使它在我的测试用例中找到了 eof 字符,当我分析其他文件时,它仍然是无限循环,因为它从未找到 eof 字符。这是编码问题还是我的文件问题?
string line = "";
unsigned long pos = 0;
ifstream curfile(input.c_str());
getline(curfile, line);
int linenumber = 0;
cout<<"About to try to read the file"<<endl;
if (!curfile.good())
cout<<"Bad file read"<<endl;
while (!curfile.eof())
{
cout<<"Getting line "<<linenumber<<endl;
linenumber++;
pos = line.find_first_of(' ');
line = line.substr(pos+1, line.size()-1);
pos = line.find_first_of(' ');
current.push_back(atof(line.substr(0, pos).c_str()));
for (int i = 0; i<4; i++)
{
pos = line.find_first_of(' ');
line = line.substr(pos+1, line.size()-1);
}
pos = line.find_first_of(' ');
dx.push_back(atof(line.substr(0, pos).c_str()));
pos = line.find_first_of(' ');
line = line.substr(pos+1, line.size()-1);
pos = line.find_first_of(' ');
dy.push_back(atof(line.substr(0, pos).c_str()));
getline(curfile, line);
}
编辑:当我第一次运行循环时,currentfile.good() 返回 false...我在做什么导致它返回该值?
首先,你不应该那样检查。eof()
不回来true
until after读取失败。但你可以做得更好(也更容易)!
检查流状态并隐式转换为void*
可以用在bool
context。由于流上的大多数读取操作都会返回对流的引用,因此您可以编写一些非常简洁的代码,如下所示:
std::string line;
while(std::getline(currentfile, line)) {
// process line
}
基本上它所做的就是说“虽然我可以成功地从currentfile
,执行以下操作”,无论如何,这就是您真正想说的;-);
就像我说的,这适用于大多数流操作,因此您可以执行以下操作:
int x;
std::string y;
if(std::cin >> x >> y) {
// successfully read an integer and a string from cin!
}
EDIT:我重写你的代码的方式是这样的:
string line;
unsigned long pos = 0;
int linenumber = 0;
ifstream curfile(input.c_str());
std::cout << "About to try to read the file" << std::endl;
while (std::getline(curfile, line)) {
std::cout << "Getting line " << linenumber << std::endl;
linenumber++;
// do the rest of the work with line
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)