You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于getchar()行为的疑问:为何下述代码会两次输出‘ch is not E’?

Why does your code print "ch is not E" twice?

Let's walk through exactly what's happening here—this is a classic pitfall with getchar() that trips up a lot of folks!

First, remember how getchar() works: it reads one character at a time from the input stream, and that includes invisible control characters like the newline (\n) you create when you press the Enter key.

Let's say you run your code and type something like a then hit Enter. Here's the play-by-play:

  • The first call to getchar() grabs the a character. Since a isn't 'E', the loop runs and prints "ch is not E".
  • The loop checks the condition again, so getchar() runs a second time. This time it grabs the newline character (\n) that's still in the input stream from you pressing Enter. Since \n isn't 'E' either, the loop runs again and prints the message a second time.

Only when you type E (the E itself will trigger the loop to exit before the subsequent newline is read) will the loop stop.

A quick side note: Your code uses void main() which isn't standard C—you should use int main() and return 0 at the end. Also, getchar() returns an int (not a char) because it needs to represent the special EOF value, so storing its result in an int variable is better practice.

If you want to avoid counting the newline as a "non-E" character, you could adjust the code to skip it, like this:

#include<stdio.h>
int main() {
    int ch;
    while ( (ch = getchar()) != 'E' && ch != EOF ) {
        // Skip newline characters so we don't print for them
        if (ch == '\n') {
            continue;
        }
        printf("ch is not E\n");
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Ravi NIKKAM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:34:16