ifstream,end of line并移动到下一行? [英] ifstream, end of line and move to next line?

查看:624
本文介绍了ifstream,end of line并移动到下一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测并移动到下一行使用std :: ifstream?

how do i detect and move to the next line using 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
}

我知道很好会告诉我错误是否发生,该流不再工作一次发生。

I know good would tell me if an error happened but the stream no longer works once that happens. How can i check to see if i am at the end of line before reading another int?

推荐答案

使用ignore()忽略直到下一行:

Use ignore() to ignore everything until the next line:

 in.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

如果你必须手动操作,只需检查字符, \ n'

If you must do it manually just check othe character to see if is '\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

这可能是失败,因为你在清除坏位之前正在寻找。

This is probably failing because you are doing a seek before clearing the bad bits.

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

这篇关于ifstream,end of line并移动到下一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆