counting words from user input

Asked by At

the program cannot get out from the while loop while (c != EOF)

I have tried it in terminal

#include <stdio.h>

main() {
    int c = getchar();
    int n = 0;
    while (c != EOF) {
        if (c == ' ') {
            while (c == ' ')
                c = getchar();
        }
        else {
            ++n;
            while (c != ' ')
                c = getchar();
        }

    }
    printf("\n%d", n);
}

it should show the no of words. however it is asking for input after input

1 Answers

4
Swordfish On
  • the program cannot get out from the while loop while (c != EOF)

    That's because you don't test for EOF in the inner while-loops:

    while (c == ' ')
        c = getchar();
    

    ~>

    while (c == ' ' && c != EOF)
        c = getchar();
    
  • You tagged your question kernigham-and-ritchie. I hope you're just using the book and don't intend to also learn that pre-standard*) style of C.

  • The return type of main() is missing.
  • When a funktion takes no arguments in C it's parameter list should be void, so

    int main(void)
    
  • I'd suggest you do

    int ch;
    while ((ch = getchar()) != EOF) {
        // process ch
    }
    
  • c == ' '
    

    There is other whitespace besides space. See <ctype.h> for a list of funktions for character classification.


Example:

#include <stddef.h>   // size_t
#include <stdbool.h>  // bool, true, false
#include <ctype.h>    // isalnum()
#include <stdio.h>    // getchar(), printf()

int main(void)
{
    size_t num_words = 0;
    bool in_word = false;
    int ch;

    while ((ch = getchar()) != EOF) {
        if (!in_word && isalnum(ch)) {  // new word begins. isalnum() or isalpha()
            in_word = true;             // ... depends on your definition of "word"
            ++num_words;
            continue;  // continue reading
        }
        else if (in_word && isalnum(ch)) {  // still inside a word
            continue;  // continue reading
        }

        in_word = false;  // when control gets here we're no longer inside a word
    }  // when control reaches the end of main() without encountering a return statement
       // the effect is the same as return 0; since C99 *)

    printf("Number of words: %zu\n\n", num_words);
}

For better variable-locality maybe a for-loop should be preferred:

for (int ch; (ch = getchar()) != EOF;)  // ...


*) Language Standards:
C99: ISO/IEC 9899:TC3
C11: ISO/IEC 9899:201x (draft close to the final standard)
C18: ISO/IEC 9899:2017 (proposal)