cwindowsgccoutputprintf

printf() prints only the first character


Recently I came across an example from the book "The C Programming Language" and decided to run it:

#include <stdio.h>

#define IN 1
#define OUT 0

int main() {

    int c, nl, nw, nc, state; 

    state = OUT; 
    nl = nw = nc = 0; 
    while ((c = getchar()) != EOF) {
        ++nc; 
        if (c == '\n') 
            ++nl;
        if (c == ' ' || c == '\n' || c == '\t') 
            state = OUT;
        else if (state == OUT) {
            state = IN; 
            ++nw;
        } 
    }
    printf("%d %d %d\n", nl, nw, nc);
}

There is a problem related to printf(). For some reason, only the first character is printed, although there should be 3 of them. What could be the problem?

System - Windows. For editing code I use Visual Studio Code. Compiler - gcc.

Interesting fact: on macOS this problem do not occur and the output is as needed.

Input:

a       
ab 
abc
abcd

Output:

4

Desired output:

4 4 14

Thanks in advance!

ANSWER:

I used control-C thinking that it was suitable as an EOF-indicator. The correct option is to use control-Z.


Solution

  • The idea here is:

    I am not sure I understand the question, but here is the output for this file

    one another
    one
    another
    
    3 4 24
    

    And it seems ok. Note that is you are testing this interactively control-Z is the EOF indicator.