c++arraysfor-loopc-stringsisspace

I need to return number of words in c sting after taking user input


I need to make a program that takes input from the user and then return the number of words entered to the string. I store user input in array char words[256]; I have a function called countWords. It loops though the array and if it encounters a space he counter is increased. if(words[i] == '\0') if the null character is reached the counter is stopped. It then return nSpaces + 1 to account for the first word.

But my output seems to produce the number of characters in the string instead. How can this be fixed.

#include <iostream>
#include <cstdlib>
using namespace std;

//Function Prototype
int countWords(char words[]);

int main(){

    char words[256];

    cout << "Enter a sentence: ";
    cin.getline(words, 256);

    int word_num = countWords(words);
    cout << "The number of words in a string is: " << word_num << endl;

    system("PAUSE");
    return 0;
}

int countWords(char words[]){
    int nSpaces = 0;
    //unsigned int i = 0;

    /*while(isspace(words[i])){
        i++;
    }*/

    for (int i=0; i<256; i++){
        if(isspace(words[i])){
           nSpaces++;
            // Skip over duplicate spaces & if a NULL character is found, we're at the end of the string
            //while(isspace(words[i++]))
                if(words[i] == '\0')
                    nSpaces--;
        }
    }
    // The number of words = the number of spaces + 1
    return nSpaces + 1;
}

The Output is:

Enter a sentence: Yury Stanev
The number of words in a string is: 7

Solution

  • You're not stopping the loop when you get to the null character. You're only testing for the null character inside the if(isspace(words[i])) block, but if the character is a space then it can't also be the null terminator. As a result, you're reading past the end of the input, and counting the spaces in the uninitialized part of the string.

    int countWords(char words[]){
        int nSpaces = 0;
    
        for (int i=0; i<256 && words[i] != '\0'; i++){
            if(isspace(words[i])){
                nSpaces++;
            }
        }
        // The number of words = the number of spaces + 1
        return nSpaces + 1;
    }