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

17 c++ fstream

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

Dou*_* T. 27

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

ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
   ...
Run Code Online (Sandbox Code Playgroud)

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

  • 可以使用stream.ignore().见下文. (2认同)

Mar*_*ork 23

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

ifstream stream("filename.txt");

// Get and drop a line
stream.ignore ( std::numeric_limits<std::streamsize>::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.
Run Code Online (Sandbox Code Playgroud)

读取文件时常见的错误:

while( someStream.good() )  // !someStream.eof()
{
    getline( someStream, line );
    cout << line << endl;
}
Run Code Online (Sandbox Code Playgroud)

这会失败,因为:当读取最后一行时,它不会读取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;
    }
}
Run Code Online (Sandbox Code Playgroud) 正确的解决方案:
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;
}
Run Code Online (Sandbox Code Playgroud)