【问题标题】:How do I read a text file from the second line using fstream?如何使用 fstream 从第二行读取文本文件?
【发布时间】:2010-09-14 22:16:02
【问题描述】:

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

【问题讨论】:

  • 您的问题实际上应该被表述为“我如何在不使用 getline() 获取第一行并继续的情况下开始阅读第二行”,那么人们不会给你那个答案,你不会不必因为他们不通灵而对他们投反对票。

标签: c++ fstream


【解决方案1】:

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

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

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

【讨论】:

  • 使用免费的 std::getline 函数会更干净一些。
  • 可以使用stream.ignore()。见下文。
【解决方案2】:

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

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

【讨论】:

  • 技术上将流转换为 void*,而不是 bool,但想法是一样的。它也调用fail(),not good(),但我认为它也应该适用于大多数eof情况。
  • @GregRogers:如果你想学究气。那么不,你是不正确的。从技术上讲,在 C++03 中,流大小写为 {unspecified-bool-type}(可以是 void*),但想法是一样的。在 C++11 中,此问题已得到修复,现在它们转换为 bool。
【解决方案3】:

更有效的方法是使用 std::istream::ignore

忽略字符串
for (int currLineNumber = 0; currLineNumber < startLineNumber; ++currLineNumber){
    if (addressesFile.ignore(numeric_limits<streamsize>::max(), addressesFile.widen('\n'))){ 
        //just skipping the line
    } else 
        return HandleReadingLineError(addressesFile, currLineNumber);
}

HandleReadingLineError 当然不是标准的,而是手工制作的。 第一个参数是要提取的最大字符数。如果这恰好是 numeric_limits::max(),则没有限制: cplusplus.com 链接:std::istream::ignore

如果您要跳过很多行,则绝对应该使用它而不是 getline:当我需要跳过文件中的 100000 行时,它需要大约一秒钟,而使用 getline 需要 22 秒。

【讨论】:

    【解决方案4】:

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

    【讨论】:

      【解决方案5】:
      #include <iostream>
      #include <fstream>
      #include <string>
      
      using namespace std;
      
      int main()
      {
      string textString;
      string anotherString;
      ifstream textFile;
      textFile.open("TextFile.txt");
      if (textFile.is_open()) {
          while (getline(textFile, textString)){
              anotherString = anotherString + textString;
          }
      }
      
      std::cout << anotherString;
      
      textFile.close();
      return 0;
      }
      

      【讨论】:

        【解决方案6】:

        此代码可以从文件中的指定行读取文件,但您必须事先在文件资源管理器中创建文件,我的文件名为“temp”,代码如下

        https://i.stack.imgur.com/OTrsj.png

        希望对你有帮助

        【讨论】:

        【解决方案7】:

        您可以使用如下忽略功能:

        fstream dataFile("file.txt");
        dataFile.ignore(1, '\n'); // ignore one line
        

        【讨论】:

          【解决方案8】:
          #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;
          }
          

          【讨论】:

          • while (!myfile.eof() ):在您尝试读取行尾之后失败。所以最后一行可以打印两次。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-01
          • 1970-01-01
          • 2021-07-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多