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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/164344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:24:00  来源:igfitidea点击:

How do I read a text file from the second line using fstream?

c++fstream

提问by Martin York

How can I make my std::fstreamobject start reading a text file from the second line?

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

回答by Doug T.

Use getline() to read the first line, then begin reading the rest of the stream.

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

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

(Changed to std::getline (thanks dalle.myopenid.com))

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

回答by Martin York

You could use the ignore feature of the stream:

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

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.

A common mistake for reading a file:

读取文件的常见错误:

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

This fails because: When reading the last line it does not read the EOF marker. So the stream is still good, but there is no more data left in the stream to read. So the loop is re-entered. std::getline() then attempts to read another line from someStream and fails, but still write a line to std::cout.

这失败是因为:读取最后一行时,它没有读取 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;
}

回答by Arthur P. Golubev

The more efficient way is ignoring strings with std::istream::ignore

更有效的方法是使用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 is not standart but hand-made, of course. The first parameter is maximum number of characters to extract. If this is exactly numeric_limits::max(), there is no limit: Link at cplusplus.com: std::istream::ignore

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

If you are going to skip a lot of lines you definitely should use it instead of getline: when i needed to skip 100000 lines in my file it took about a second in opposite to 22 seconds with getline.

如果你要跳过很多行,你肯定应该使用它而不是 getline:当我需要在我的文件中跳过 100000 行时,它花了大约一秒钟,而 getline 只需要 22 秒。

回答by Adam

Call getline() once to throw away the first line

调用 getline() 一次以丢弃第一行

There are other methods, but the problem is this, you don't know how long the first line will be do you? So you can't skip it till you know where that first '\n' is. If however you did know how long the first line was going to be, you could simply seek past it, then begin reading, this would be faster.

还有其他方法,但问题是这个,你不知道第一行要多久吗?所以你不能跳过它,直到你知道第一个 '\n' 在哪里。但是,如果您确实知道第一行要多长时间,您可以简单地寻找它,然后开始阅读,这会更快。

So to do it the first way would look something like:

所以要做到这一点,第一种方式看起来像:

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

回答by Aaron Sterling

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

回答by Chabs

this code can read file from your specified line from file but you have to make file in file explorer before hand my file name is "temp" code is given below

此代码可以从文件中的指定行读取文件,但您必须先在文件资源管理器中创建文件,然后我的文件名是“临时”代码,如下所示

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

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

hope this can help

希望这可以帮助

回答by Sina Raoufi

You can use ignore function as follow:

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

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

回答by m_pGladiator

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