13

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
SexyBeastFarEast
  • 143
  • 1
  • 1
  • 7
  • What is your use case for this? Sounds a bit like an XY problem. – Kerrek SB Apr 22 '12 at 14:44
  • 2
    its to read a text file and from it i want to use a peek() like function to determine if the next value that reading in is a sentential string or not. the method below worked perfectly for my problem. – SexyBeastFarEast Apr 24 '12 at 07:22

1 Answers1

21

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;
}
Kleist
  • 7,785
  • 1
  • 26
  • 30