Here is a small example of C++ code on how to read a characters from a file as well as to count the number lines of any particular file consist of. The code will check for "\n" the "new line character" and increase the number of lines stored in number_of_lines integer variable. Every iteration will also print single character including "\n" to an output.
First create a file called my-input-file.txt which will contain some text. For example:

welcome to
linuxconfig.org
c++

Then copy c++ code below to a file called read-characters.cpp:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

ifstream fin;
fin.open("my-input-file.txt", ios::in);

char my_character ;
int number_of_lines = 0;

while (!fin.eof() ) {

fin.get(my_character);
cout << my_character;
if (my_character == '\n'){
++number_of_lines;
}
}
cout << "NUMBER OF LINES: " << number_of_lines << endl;

}

and compile it with:

g++ read-characters.cpp -o read-characters

Execute new compiled binary file:

./read-characters

NOTE: your text file must be located in the same directory as your executable read-characters program.

NOTE: while loop and fin.get will add extra new line character so you may start with :

int number_of_lines = -1

OUTPUT:

welcome to
linuxconfig.org
c++

NUMBER OF LINES: 4

Free Linux eBooks

Linux Technical Writer

LinuxCareer, Casual, Volunteer, Home Based

Do you wish to join Linuxcareer.com project and find out how to be a technical writer? We are now looking for volunteers to help us write tutorials and share them with Linux community

  • Casual work from home
  • 10 articles / year

Any active Linuxcareer.com’s author will be entitled to following benefits:

  • actively participate in Linuxcareer.com’s decision making process
  • feedback and help

APPLY

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Linux Online Training

Learn to run Linux servers and prepare for LPI certification with Linux Academy. 104 available video lessons with PDF course notes with your own server!

Go to top