In this article we will discuss how to read a file line by line and put them in a vector or perform some other operation each line.

Reading File line by line

First open the file i.e.

Now keep reading next line using getline() and push it in vector function until end of file i.e.

Complete example is as follows:

Reading file line by line and performing operations on each line

Many times we encounter scenarios where we need to read a file line by line and perform some operation on each line like,

  • Search something in each line.
  • Modify the content
  • Store the string to some container etc.

We can a make a generic function that will accept a callback or function pointer along with File name i.e.

It will read the file line by line and will call the given function on each line.

Checkout complete example as follows,

To compile the above examples use following command on linux,

g++ –std=c++11 example.cpp

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.