1

So this is the code. And I expected it to work. It should let me enter input and then tell me the number of blanks, digits, letters and others. But it just giving input and its not giving me the output.

#include <stdio.h>

int main(void)
{
    int blanks = 0, digits = 0, letters = 0, others = 0;
    char c;

    printf("Im working");

    while ((c = scanf("%c", &c)) != EOF)
    {
        if (c == ' ')
            ++blanks;
        else if (c >= '0' && c <= '9')
            ++digits;
        else if (c >= 'a' && c <= 'z')
            ++letters;  
        else if (c >= 'A' && c <= 'Z')
            ++letters;
        else
            ++others;
    };

    printf("blanks = %d, digits = %d, letters = %d, others = %d\n\n",
           blanks, digits, letters, others);
    return 0;      
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
dipanshu
  • 21
  • 2
  • 4
    Your code reads input until it reaches end-of-file (EOF). You need to end standard input. In a typical Linux/unix terminal, this is Ctrl+D. – Jonathon Reinhart Jul 25 '23 at 13:30
  • 6
    `c = scanf("%c", &c)` You need to read the documentation for `scanf` again. You overwrite the scanned character with the return value immediately. The return value is not the same as the converted input. – Gerhardh Jul 25 '23 at 13:31
  • So it worked when i refereed it to a txt file with text but it doesnt read input from command line cause i tried like 100 times. But it works when i refer it txt file. – dipanshu Jul 25 '23 at 13:48
  • 2
    Does any answer in [How to send EOF via Windows terminal](https://stackoverflow.com/q/16136400) help? – jps Jul 25 '23 at 13:59
  • 1
    *"it worked when i refereed it to a txt file"* We may not share the same definition of "worked" (I doubt it gave the correct results). Anyways, i'd use `while ( scanf("%c", &c) == 1 )`. – Bob__ Jul 25 '23 at 14:37
  • `scanf` is a disaster for the beginner. Since you are just reading one character at a time, you should consider `int c; while( (c = getchar()) != EOF ){ ... ` – William Pursell Jul 25 '23 at 14:57

1 Answers1

2

The code will read standard input until end of file. In order to signal the end of file from the terminal, you should type Ctrl-D (on unix systems) or Ctrl-Z (on Windows) and hit the Enter key.

Note however that you overwrite c in the test while ((c = scanf("%c", &c)) != EOF), so the character classification tests will only increment others. You should instead just test the return value:

    while (scanf("%c", &c) != EOF)

Alternatively, you could define c as an int and write:

    while ((c = getchar(c)) != EOF)
chqrlie
  • 131,814
  • 10
  • 121
  • 189