I am trying to create a program that, after inputing a text file, can:
1) Count number of lines in the text file.
2) Count number of words in the file.
3) Count number of characters in the file including white spaces.
4) Count number of characters in the file excluding white spaces.
I have written the following code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream file("wordcount.txt");
string s1;
int words=0, lines=0, ch_spaces=0, ch_nspaces=0;
while (!file.eof())
{
getline(file, s1);
ch_spaces += s1.size();
lines++;
}
file.clear();
file.seekg(0, ios::beg);
while (!file.eof())
{
file >> s1;
words++;
}
cout << "The file contains " << ch_spaces << " characters (including spaces)\n";
cout << "The file contains " << ch_nspaces << " characters (excluding spaces)\n";
cout << "The file contains " << words << " words.\n";
cout << "The file contains " << lines << " lines.\n";
system("pause");
return 0;
}
It fulfills the first three requirements. But I can't think of a method to count number of characters without white spaces (spaces, tabs etc.)
Can someone please help me with this??? I am thinking on two approaches.
1) Count the number of spaces and subtract it from ch_spaces.
2) Trim the text on a line by line bases and count the number of characters in it in a similar way as I counted ch_spaces.
If someone can help me in implementing any of these two approaches than it would be great too.
Thanks in advance!!!!!!!!!