首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用fstream从第二行读取文本文件?

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

Stack Overflow用户
提问于 2008-10-02 20:13:45
回答 7查看 88.6K关注 0票数 18

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

EN

回答 7

Stack Overflow用户

发布于 2008-10-02 20:15:38

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

代码语言:javascript
运行
复制
ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
   ...

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

票数 27
EN

Stack Overflow用户

发布于 2008-10-02 21:29:44

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

代码语言:javascript
运行
复制
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.

读取文件时的一个常见错误:

代码语言:javascript
运行
复制
while( someStream.good() )  // !someStream.eof()
{
    getline( someStream, line );
    cout << line << endl;
}

这失败的原因是:当读取最后一行时,它没有读取EOF标记。因此,流仍然是好的,但是流中没有更多的数据可供读取。因此,循环被重新进入。然后,std::getline()尝试从someStream读取另一行并失败,但仍将一行写入std::cout。

简单的解决方案:

代码语言:javascript
运行
复制
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;
    }
}

正确的解决方案:

代码语言:javascript
运行
复制
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;
}
票数 27
EN

Stack Overflow用户

发布于 2008-10-02 20:18:39

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

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

因此,第一种方法看起来像这样:

代码语言:javascript
运行
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/164344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档