I tried to write a program to find out the number of characters and words in a file:
/*
Write C++ program to count:
Number of characters in a file
Number of words in a file
Number of lines in a file
*/
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int countOfCharacters = 0;
int countOfWords = 0;
ifstream ins;
ins.open("hello.txt", ios::in);
char c;
while (ins.get(c))
{
countOfCharacters += 1;
}
cout << "Total Number of characters is " << countOfCharacters << endl;
ins.seekg(0,ios::beg);
while(ins.get(c))
{ cout << "Character is " << c <<endl;
if (c==' ' || c=='.' || c=='\n'){
countOfWords+=1;
}
}
cout << "Total number of words in the file is " <<countOfWords <<endl;
ins.close();
return 0;
}
For the following input:
Hi Hello Girik Garg
I get the output as:
Total Number of characters is 19
Total number of words in the file is 0
Can someone tell why I am not getting the right number of Words?
When you reach the end of the file in the first read routine eofbit
flag is set to true
, in order to be able to read from the same stream without closing/reopening it, you need to reset it:
//...
ins.clear(); //<--
ins.seekg(0, ios::beg);
//...
That being said, you could do both counts in the same cycle, as suggested by @YSC:
while (ins.get(c))
{
countOfCharacters += 1;
if (c == ' ' || c == '.' || c == '\n')
{
countOfWords += 1;
}
}
Note that if the line doesn't end with a \n
(or '.'
/' '
) the last word is not counted, and you should verify if the stream is indeed open:
if(ins.is_open(){ /*...*/}