学习《C程序设计语言(第2版)》时,使用printf()输出数组内容遇异常的问题求助
Hey there! Let's unpack exactly what's going on with your program and answer your questions clearly.
First: Why Isn't the Array Printing, and Why Isn't the Final printf() Running?
The short answer is: your program never got to those lines yet.
When you entered the sequence 12333 45666 789 and hit enter, the program processed those characters (updating the ndigit array, nwhite, etc.), but it stayed stuck inside the while ((c = getchar()) != EOF) loop. It was still waiting for more input because it hadn't received the "end of input" (EOF) signal. The partial output you saw (digits = 0^C) happened because you pressed Ctrl+C to force-quit the program mid-execution—only the first part of the print logic ran before the program was killed.
The Root Cause: EOF and Line-Buffered Input on Windows
Let's break down how standard input works in your Windows 10 environment:
- Keyboard input in Windows consoles uses line buffering: characters you type are stored in a buffer until you press Enter, at which point the buffer is sent to your program.
- The
whileloop only exits whengetchar()returnsEOF, which tells the program "there's no more input to read". - On Windows, you can't just type EOF directly. To send the EOF signal to your program, you need to:
- Press Ctrl+Z (this inserts the EOF marker into the input buffer)
- Press Enter (this flushes the buffer and sends the EOF to your program)
Once you do that, the while loop exits, and your program proceeds to run all the print statements—including the full array output and the final line with whitespace/other counts.
Quick Test to Confirm
Try this sequence instead:
- Run your compiled program
- Type
12333 45666 789and press Enter - Press Ctrl+Z, then press Enter
You'll see the program output your expected result:
digits = 0 1 1 3 1 1 3 1 1 1, white space = 2, other = 0
Your code itself is correct—this is just a quirk of how input handling works on Windows compared to Unix-like systems (where Ctrl+D sends EOF directly).
内容的提问来源于stack exchange,提问作者DrBwts

