-2

it's the K and R c programming exercise, I don't know why my program doesnt work, could anyone help, please and thank you.

When I run the program and type a line of words or two and hit 'Enter', it doesnt show anything, it just jumps to the next line and thats it

#include <stdio.h>

int main()
{
     int c, line, tab, blank;
    
    line = 0;
    tab = 0;
    blank = 0;
    
    while ( (c = getchar()) != EOF)
    {
        if (c == '\n')
            ++line; 

        if (c == '\t')
            ++tab;

        if (c == ' ')
            ++blank;
       
    }
    
    printf("Lines: %d\n Tabs: %d\n Blanks: %d\n", line, tab, blank);

    return 0;
}
kaylum
  • 13,833
  • 2
  • 22
  • 31
Chihiro
  • 1
  • 2
  • 2
    And please describe the problem better than "doesn't work". Give the exact input, expected result and actual result. – kaylum Nov 17 '20 at 21:40
  • 1
    What doesn't work? Wrong counts, does not end, crashes, what? I compiled and ran it, no problem. – Weather Vane Nov 17 '20 at 21:40
  • 2
    OT: your formatting of the `if` clauses is most strange and very unreadable. – Jabberwocky Nov 17 '20 at 21:41
  • @kaylum yes you're right, sorry for not being clear, basically when I run the program and type a line of words or two and hit 'Enter', it doesnt show anything, it just jumps to the next line and thats it – Chihiro Nov 17 '20 at 21:42
  • 1
    You need to type the `EOF` that the program is looking for: Ctrl-D on Linux, Ctrl-Z on Windows. Or direct a file to the input. – Weather Vane Nov 17 '20 at 21:43
  • FYI, I have edited your code to show you the standard way that code blocks are indented. Each child block should be indented relative to the parent. And I haven't shown it but best practice is also to enclose even single line `if` bodies with `{ }` – kaylum Nov 17 '20 at 21:46
  • @WeatherVane could you please explain more – Chihiro Nov 17 '20 at 21:53
  • Well if you run the program like `program < textfile.txt` then the contents of that text file are input to `stdin` instead of from the keyboard. At the end of the file, the program receives `EOF` even though there isn't an actual character like that in the file. Otherwise you have to type it. Windows is fussy though. The Ctrl-Z must be directly after a `Enter` is typed and then another `Enter` must be typed. – Weather Vane Nov 17 '20 at 21:55
  • @WeatherVane thank you very much, now I see why it shows nothing. – Chihiro Nov 17 '20 at 22:05
  • @Jabberwocky Ill keep that in mind, thanks – Chihiro Nov 17 '20 at 22:05
  • @kaylum noted, thanks! – Chihiro Nov 17 '20 at 22:05

1 Answers1

0

When do you think will EOF occur, if you are reading from stdin? You need either signal handling or a terminating character.

Erdal Küçük
  • 4,810
  • 1
  • 6
  • 11