C++ fstream read text file line by line

Introduction

To create an std::fstream object we use:

#include <fstream> 

int main() 
{ 
    std::fstream fs{ "myfile.txt" }; 
} 

This example creates a file stream called fs and associates it with a file name myfile.txt on our disk.

To read from such file, line-by-line, we use:

#include <iostream> 
#include <fstream> 
#include <string> 

int main() //  w  w  w  .  jav  a  2 s.c o m
{ 
    std::fstream fs{ "myfile.txt" }; 
    std::string s; 
    while (fs) 
    { 
        std::getline(fs, s); // read each line into a string 
        std::cout << s << '\n'; 
    } 
} 

Once associated with a file name, we use our file stream to read each line of text from and print it out on a screen.

To do that, we declare a string variable s which will hold our read line of text.

Inside the while-loop, we read a line from a file to a string.

This is why the std::getline function accepts a file stream and a string as arguments.

Once read, we output the text line on a screen.

The while loop terminates once we reach the end of the file.




PreviousNext

Related