C++ fstream函数读取不提取行的方法是什么?

13
在C++中,fstream库(或任何库)中是否有一个函数可以让我读取到'\n'分隔符而不进行提取操作?
我知道peek()函数可以让程序查看下一个要读入的字符而不进行提取,但我需要类似于peek()函数的功能,但是用于整行读取。

你使用这个的场景是什么?听起来有点像 XY 问题。 - Kerrek SB
2
我想读取一个文本文件,并使用类似于peek()的函数来确定下一个读入的值是否为句子字符串。下面的方法完美地解决了我的问题。 - SexyBeastFarEast
1个回答

21

您可以通过结合使用getlinetellgseekg来实现此操作。

#include <fstream>
#include <iostream>
#include <ios>


int main () {
    std::fstream fs(__FILE__);
    std::string line;

    // Get current position
    int len = fs.tellg();

    // Read line
    getline(fs, line);

    // Print first line in file
    std::cout << "First line: " << line << std::endl;

    // Return to position before "Read line".
    fs.seekg(len ,std::ios_base::beg);

    // Print whole file
    while (getline(fs ,line)) std::cout << line << std::endl;
}

谢谢 Kleist,这个方法完美地运行了!那么我假设没有像 peek() 这样读取一行的函数? - SexyBeastFarEast
2
确实,没有这样的peek函数。 - Kleist
1
tellg返回std::streampos,因此应该使用它而不是int。 - user2746401
遗憾的是,这不能在一个“const”函数中使用,并且它可能不是线程安全的。 - Ivan Rubinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接