[英]ifstream, end of line and move to next line?
我如何使用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
}
我知道很好會告訴我是否發生了錯誤,但一旦發生這種情況,流不再有效。 如何在閱讀另一個int之前檢查我是否在行尾?
使用ignore()忽略所有內容,直到下一行:
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
如果你必須手動完成,只需檢查其他字符,看看是否'\\ 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
這可能是失敗的,因為您在清除壞位之前正在進行搜索。
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
您應該使用in.clear();
清除流的錯誤狀態in.clear();
在循環之后,流將再次起作用,就像沒有發生錯誤一樣。
您還可以將循環簡化為:
while (in >> v) {
cout << v << " ";
}
in.clear();
如果操作成功,則流提取返回,因此您可以直接測試它,而無需顯式檢查in.good();
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.