C++ fstream function that reads a line without extracting?

六月ゝ 毕业季﹏ 提交于 2019-12-08 15:40:16

问题


In C++, is there a function in the fstream library (or any library) that allows me to read a line to a delimiter of '\n' without extracting?

I know the peek() function allows the program to 'peek' at the next character its reading in without extracting but I need a peek() like function that does that but for a whole line.


回答1:


You can do this with a combination of getline, tellg and seekg.

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


来源:https://stackoverflow.com/questions/10268872/c-fstream-function-that-reads-a-line-without-extracting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!