0

I am writing a code where I am supposed to find the number of words in a string, knowing that each word can be delimited by any character other than A-Z (or a-z). The code I wrote works fine only when there is no punctuation at the beginning of the sentence. But the trouble comes when start the sentence with punctuation such as quotation marks (i.e. "Only connect." will display as a result 3 words instead of 2). I am programming in C++ using Dev-C++. Your help will be appreciated. My code is below:

#include <cstring>
#include <iostream>
#include <conio.h>
#include <ctype.h>

using namespace std;

int getline();   //scope
int all_words(char prose[]);  //scope

int main()
{
   getline();
   system ("Pause");
   return 0;
}


int getline()
{
    char prose[600];
    cout << "Enter a sentence: ";

    cin.getline (prose, 600); 
    all_words(prose);
    return 0;
}


int all_words(char prose[])
{ int y, i=0, k=0; int count_words=0; char array_words[600], c;

    do
     {

        y=prose[i++];
        if (ispunct(y))  //skeep the punctuation
         i++;

         if ((y<65 && isspace(y)) || (y<65 && ispunct(y)))     //Case where we meet spacial character or punctuation follwed by space

          count_words++;   //count words

         if (ispunct(y))  //skeep the punctuation
           i++;

    }while (y); //till we have a character

    cout <<endl<<" here is the number of words  "<< count_words <<endl;

   return 0; 

 }



 ***********************************Output******************************
  Enter a sentence: "Only connect!"

  here is the number of words  3

  Press any key to continue . . .
T4000
  • 231
  • 1
  • 7
  • 24

2 Answers2

2

I think you need to rethink your algorithm. Of the top of my head, I might do it something like this:

  • Loop while not end of string
    • Skip all non-alphabetic characters (while (!std::isalpha))
    • Skip all alphabetic characters (while (std::isalpha))
    • Increase word-counter

Remember to check for end of the string in those inner loops as well.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

First

if (ispunct(y))

On first quotation mark you've increment counter i, but var y still contain ", which is yield second condition as true. Last one " gives you additional increment to count_words++;

if ((y<65 && isspace(y)) || (y<65 && ispunct(y)))

Anyway you task is just to split string to tokens and count them. Example solutions can be found here here.

Community
  • 1
  • 1
Sergei Nikulov
  • 5,029
  • 23
  • 36