Search code examples
cgetchar

How do I get this getchar() function inside this while loop to return a value? (C)


So I'm unfamiliar with the getchar() function in C (because I'm new to programming).
I want to know how to make the code below take a number of characters (whether thru a file or by inputting from keyboard) and count them with a while loop which has the getchar() function.
I want it to read up until the end of a file (or keyboard input). As of right now the code doesn't return anything (even if you type in the commandline).
The OS I'm running this code from is Windows.

#include <stdio.h>

int main(void){
    
    int blanks = 0, digits = 0, letters = 0, others = 0;
    int c; //use for actual integer value of character
    printf("WELCOME TO WHILE CHARACTER COUNTER: WRITE ANY CHARACTER:\n");
    
    while ((c = getchar()) != EOF){
        if (c == ' ') //counts any blanks on a text
            ++blanks;
        else if (c >= '0' && c <= '9')
            ++digits;
        else if (c >= 'a' && c <= 'z' || c >= 'A' &&  c<= 'Z') 
            ++ letters; 
        else
            ++ others;
}
printf ("\nNumber of:blank characters = %d, digits = %d, letters = %d", blanks, digits, letters);

printf ("\nOther characters = %d", others);

return 0; 
}


Solution

  • Your code works, in principle. For the input This is a test. followed by the newline character, followed by end-of-file, your program has the following output:

    WELCOME TO WHILE CHARACTER COUNTER: WRITE ANY CHARACTER:
    
    Number of:blank characters = 3, digits = 0, letters = 11
    Other characters = 2
    

    Click this link to test your program yourself with that input.

    I suspect that your problem is rather one of the following:

    • You don't know how to execute your program in such a way that input is redirected from a file.

    • You don't know how to enter end-of-file on the keyboard.

    In order to call your program in such a way that input is redirected from a file, on most operating systems, you can call your program the following way:

    myprogramname < inputfile.txt

    When you are reading input from a terminal/console, you can enter end-of-file the following way:

    • On Linux, you can use the keyboard combination CTRL+D.
    • On Microsoft Windows, you can use the keyboard combination CTRL+Z.