当前位置:  开发笔记 > 编程语言 > 正文

如何使用fstream从第二行读取文本文件?

如何解决《如何使用fstream从第二行读取文本文件?》经验,为你挑选了2个好方法。

如何让我的std::fstream对象从第二行开始读取文本文件?



1> Doug T...:

使用getline()读取第一行,然后开始读取流的其余部分.

ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
   ...

(更改为std :: getline(感谢dalle.myopenid.com))


可以使用stream.ignore().见下文.

2> Martin York..:

您可以使用流的忽略功能:

ifstream stream("filename.txt");

// Get and drop a line
stream.ignore ( std::numeric_limits::max(), '\n' );

// Get and store a line for processing.
// std::getline() has a third parameter the defaults to '\n' as the line
// delimiter.
std::string line;
std::getline(stream,line);

std::string word;
stream >> word; // Reads one space separated word from the stream.

读取文件时常见的错误:

while( someStream.good() )  // !someStream.eof()
{
    getline( someStream, line );
    cout << line << endl;
}

这会失败,因为:当读取最后一行时,它不会读取EOF标记.因此流仍然很好,但流中没有剩余数据可供读取.所以循环重新进入.然后std :: getline()尝试从someStream读取另一行并失败,但仍然向std :: cout写一行.

简单方案:
while( someStream ) // Same as someStream.good()
{
    getline( someStream, line );
    if (someStream) // streams when used in a boolean context are converted to a type that is usable in that context. If the stream is in a good state the object returned can be used as true
    {
        // Only write to cout if the getline did not fail.
        cout << line << endl;
    }
}
正确的解决方案:
while(getline( someStream, line ))
{
    // Loop only entered if reading a line from somestream is OK.
    // Note: getline() returns a stream reference. This is automatically cast
    // to boolean for the test. streams have a cast to bool operator that checks
    // good()
    cout << line << endl;
}

推荐阅读
Life一切安好
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有