Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Word counter returning incorrect number of words [SOLVED]

I’ve been trying to create a program that reads text from a file and stores it in a string. I feed the string to a function that counts every word in the string.

However its only accurate assuming the user leaves some whitespace at the end of a line and doesn’t creates blank lines…. not a very good word counter.

  • Creating a blank line results in a false increment to the word count.

I’m not sure if my main problem is using a boolean to do this or checking for whitespace and ‘\n’ characters.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bool countingLetters = false;
int wordCount = 0;
for (int i = 0; i < text.length(); i++)
{
    if (text[i] == ' ' && countingLetters == true)
    {
        countingLetters = false;
        wordCount++;
    }
    if (text[i] != ' ' && countingLetters == false)
    {
        countingLetters = true;
    }
    if (text[i] == '\n' && countingLetters == true)
    {
        countingLetters = false;
        wordCount++;
    }
}

>Solution :

An alternative is to count the beginning of a "word".

Let us say the beginning of a word is a letter after a non-letter. We can adjust this if desired.

int wordCount = 0;
int prior = '\n';  // some non-letter
for (int i = 0; i < text.length(); i++) {
  if (isalpha(text[i]) && !isalpha(prior)) {
    wordCount++;
  }
  prior = text[i];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading