My C program to count and print the number of words in a program doesn't work

Viewed 66

I'm new to C. I was reading Kernigham Ritchie, and came across this example which shoes a code to count the numbers of words in the input. It was quite complex, and I was determined to write a simpler one, but my effort didn't go so well. I can't find an error in my reasoning, so please help.

I am new to C, but I have some experience in Python from my senior year of high school.

#include <stdio.h>

int main()
{
//Defining the variables
    int c, nw;
    nw=0;
    
//Creating the main loop to traverse the input
    while (!(c=getchar()== EOF)) {
        
       //Creating a condition to check whether a space or a tab has been put.
        if(c==' '||c=='\t') {
            ++nw;
        }
    
        
        else{
            ;
        }
        
    }
    printf("The number of words is ");
    printf("%i", nw);
    return 0;
}

The output is all right, however, it shows number of words as 0.

3 Answers

The condition in the while loop looks like

while ( !( c = ( getchar()== EOF ) ) ) {

that is the integer variable c gets the value 0 in case the user enters a valid character. That is the variable c gets the value of the expression getchar()== EOF

It seems you mean

while ( ( c=getchar() ) != EOF ) {

Pay attention to that if the user will enter for example two spaces then the program will count incorrectly the number of words due to this if statement

    if(c==' '||c=='\t') {
        ++nw;
    }

Also the user can press Enter and the input buffer will contain the new line character '\n' that also separates word.

You missed "operator precedence" in this code: (c=getchar())!= EOF, means first get the char and then compare with EOF. This should work:

#include <stdio.h>

int main()
{

    int c, nw;
    nw=0;
    
    while ((c=getchar())!= EOF) 
    {
        
        if(c==' '||c=='\t') 
        {
            ++nw;
        }
        
    }
    
    printf("The number of words is ");
    printf("%i", nw);
    return 0;
}

You can try it this way

#include <stdio.h>
#include <string.h>
 
void main()
{
    char word[200] = "Keith Tumusiime and everything i need";
    int count = 0, i;
 
    
    for (i = 0;word[i] != '\0';i++)
    {
    //a space is a break point to tell that you are starting a ney word
        if (word[i] == ' ' && word[i+1] != ' ')
            count++;    
    }
    printf("Number of words in given string are: %d\n", count + 1);
}

//Or count wat the user has enterd

printf("Enter the content:\n");
scanf("%[^\n]word", word);
Related