-1

i am trying to open an text file and trying to count the numbers of characters and words in the file, i have created while " while (!infile.eof()); " to scan the whole file till the end . However only one of the function is working and other one is also printing the same answer as the first one.

#include <iostream>
#include <fstream>
#include <conio.h>

using namespace std;

int main()
{

ifstream infile;
infile.open("tomorrow.txt");


int count1_char = 0;
int count2_word = 0;

while (!infile.eof())
{
    {
        char ch;
        infile.get(ch);  //number of characters
        count1_char++;
    }
    {
        char word[30];
        infile >> word; //numner of words
        count2_word++;
    }

} 
cout << " the number of characters :" << count1_char << endl;
cout << " the number of words :" << count2_word << endl;

infile.close();

return 0;
}

the output: the number of characters :17 the number of words :17 Press any key to continue . . .

1 Answers1

5

Since words consist of characters, you cannot read characters and words separately. You should take one of two approaches:

  • Read words, and add their lengths to character count - this approach is very simple, but your code has no control over separators, or
  • Read characters, and find delimiters to decide when one word ends and another word begins - this is slightly more complex, but your program stays in full control over its input.

The advantage of the first approach is its simplicity; the advantage of the second approach is an ability to account for whitespace characters correctly.

The second approach requires you to keep a "state" that lets you distinguish if the current character is part of a new word, or a continuation of a previously found word. A simple flag is sufficient for this. You will have one loop reading characters one by one, classifying each character as a space or non-space (e.g. with std::isspace function), incrementing the character count, and doing one of three things:

  • If you see a space, reset "is inside a word" flag to "false"
  • If you see a non-space, and "is inside a word" flag is "true", do nothing
  • If you see a non-space, and "is inside a word" flag is "false", set it to "true", and increment word count.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • hey, thank you for responding my question, since this my very first time in programming I did not quite understand what you mean by " find delimiters to decide when one word ends and another word begins ". if you don't mind elaborating it, I will really appreciate it. – Abrar Sajjad Dec 27 '16 at 15:01
  • @AbrarSajjad delimeters mean how your words are separated.Like delimeter in "How are you" is `space` while in "How,are,you" is `comma`. – Gaurav Sehgal Dec 27 '16 at 16:15