我如何使用std :: ifstream检测并移动到下一行?
void readData(ifstream& in)
{
string sz;
getline(in, sz);
cout << sz <<endl;
int v;
for(int i=0; in.good(); i++)
{
in >> v;
if (in.good())
cout << v << " ";
}
in.seekg(0, ios::beg);
sz.clear();
getline(in, sz);
cout << sz <<endl; //no longer reads
}
Run Code Online (Sandbox Code Playgroud)
我知道很好会告诉我是否发生了错误,但一旦发生这种情况,流不再有效.如何在阅读另一个int之前检查我是否在行尾?
Mar*_*ork 17
使用ignore()忽略所有内容,直到下一行:
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Run Code Online (Sandbox Code Playgroud)
如果你必须手动完成,只需检查其他字符,看看是否'\n'
char next;
while(in.get(next))
{
if (next == '\n') // If the file has been opened in
{ break; // text mode then it will correctly decode the
} // platform specific EOL marker into '\n'
}
// This is reached on a newline or EOF
Run Code Online (Sandbox Code Playgroud)
这可能是失败的,因为您在清除坏位之前正在进行搜索.
in.seekg(0, ios::beg); // If bad bits. Is this not ignored ?
// So this is not moving the file position.
sz.clear();
getline(in, sz);
cout << sz <<endl; //no longer reads
Run Code Online (Sandbox Code Playgroud)
您应该使用以下命令清除流的错误状态in.clear();您应该在循环后
您还可以将循环简化为:
while (in >> v) {
cout << v << " ";
}
in.clear();
Run Code Online (Sandbox Code Playgroud)
如果操作成功,流提取就会返回,因此您可以直接测试它,而无需显式检查in.good();。