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

时间:2020-03-06 15:02:52  来源:igfitidea点击:

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

解决方案

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

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

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

一次调用getline()扔掉第一行

还有其他方法,但是问题是这样,我们不知道第一行会持续多久?因此,直到我们知道第一个'\ n'在哪里,我们才能跳过它。但是,如果我们确实知道第一行将要持续多久,则可以简单地经过它,然后开始阅读,这样会更快。

因此,第一种方式是这样的:

#include <fstream>
#include <iostream>
using namespace std;

int main () 
{
    // Open your file
    ifstream someStream( "textFile.txt" );

    // Set up a place to store our data read from the file
    string line;

    // Read and throw away the first line simply by doing
    // nothing with it and reading again
    getline( someStream, line );

    // Now begin your useful code
    while( !someStream.eof() ) {
        // This will just over write the first line read
        getline( someStream, line );
        cout << line << endl;
    }

    return 0;
}

#include <fstream>
#include <iostream>
using namespace std;

int main () 
{
  char buffer[256];
  ifstream myfile ("test.txt");

  // first line
  myfile.getline (buffer,100);

  // the rest
  while (! myfile.eof() )
  {
    myfile.getline (buffer,100);
    cout << buffer << endl;
  }
  return 0;
}

我们可以使用流的忽略功能:

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.

读取文件的常见错误:

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;
}