Problem using printf() to output the contents of an array

Viewed 90

I have started working through "The C programming language, 2nd Ed." & already I'm running into problems. This code is from Chapter 1 on arrays,

#include <stdio.h>

int main(void){

    int c, i, nwhite, nother;
    int ndigit[10];

    nwhite = nother = 0;
    for (i = 0; i < 10; ++i){
        ndigit[i] = 0;
    }

    while ((c = getchar()) != EOF){
        if (c >= '0' && c <= '9')
            ++ndigit[c - '0'];
        else if (c == ' ' || c == '\n' || c == '\t')
            ++nwhite;
        else
            ++nother;
    }

    printf("digits ="); 
    for (i = 0; i < 10; ++i){
        printf(" %d", ndigit[i]);
    }
    printf(", white space = %d, other = %d\n", nwhite, nother);
}

It compiles (gcc via Visual Studio Code, Win 10, x64) no errors or warnings. I input the following sequence via the keyboard,

12333 45666 789

and the output I get,

digits = 0^C

Now I was expecting,

digits = 0 1 1 3 1 1 3 1 1 1, white space = 2, other = 0

I then rewrote the for loop that is supposed to print the array to print out i

for (i = 0; i < 10; ++i){
        printf(" %d", i);
}

Then got,

digits = 0^C

What's going on here? First off, why isnt the array being printed, secondly why is the final printf() statement not being executed?

EDIT:: Thanks to the comments, I didn't understand the EOF character properly & how the input stream works. If I exit with ctrl+z and then enter the program executes correctly!

0 Answers
Related