-2

I need to write a program that will read in a sentence and output the number of words in the sentence. I have the program done, but the problem is that my program is counting the spaces inbetween the words as characters. How do I omit those spaces and just display the number of words in the string? I was thinking I need some type of loop, but I don't know how to execute it.

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define pause system("pause")

main() {
char mystring[155];
int counter = 0;

printf("Enter your name: ");
scanf("%[^\t\n]", &mystring); 
printf("Your name is %s\n", mystring);

// find out the number of characters in the string
counter = strlen(mystring); 
printf("There are %i words in the sentence. \n", counter);

// find out how many WORDS are in the sentence. Omit spaces



pause;
} // end of main
Matthew Young
  • 29
  • 1
  • 2
  • 4
  • HINT: think you need a loop in there and count the words, skip the punctuation characters, but I'm not going to write your program for you. – X Tian Feb 05 '13 at 19:02
  • Words or characters? You say words but your code seems to be counting chars. – P.P Feb 05 '13 at 19:10

2 Answers2

0

Again, as someone has already said, use strtok. If you need to know more about it, http://www.cplusplus.com/reference/cstring/strtok/

If you want to do it without using any existing API's (I don't know why you would want to do that unless it's a class project), then create a simple algorithm with a pointer to traverse the string and skip spaces while incrementing count.

As people have said before, this will be a good exercise for you, so don't ask for code. And there's always google..

0

Your function would look something like this :

_getNumberOfWords(char[] string) {
    int count = 0;
    for (int i=0; string[i] != '\0'; i++) {
        if (string[i] == " ") {
        for (int j=i; string[j] != '\0'; j++) {
            // This is to handle multiple spaces
            if (string[j] != " ") break;
        }
        count++;
    }
    return count;
}

You could also try to do a :

char * strtok ( char * string, const char * " " );
lokoko
  • 5,785
  • 5
  • 35
  • 68