#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
int count = 0;
ifstream FileName (“try.txt”);
if (FileName.is_open() && !FileName.eof()){
while (getline(FileName,line)){
count++;
}
}
else cout << “Error opening file!” << endl;
cout << “The number of lines in the file is ” << count << endl;
system(“pause”);
}
This program counts the number of lines in a text file. I used the getline function to count it. The getline function is used to create a string containing all of the characters from the input stream until the end of file is found or the delimiter.
Its syntax is getline(char *s, streamsize n) or getline(char *s, streamsize n, char delimiter).
The difference between them is that tche first one includes blank lines in counting while the second one contains a delimiter which can be any character depending on what you want to base your count on (e.g. newline). By replacing the getline function above with this getline(FileName, string, ‘\n’), it will count lines in the text with text and not include the blank lines.
Did find the post very useful? Maybe you want to buy me a glass of beer!






0 Comments until now.
Comment!