getChar()跳过c程序中的输入

问题描述 投票:0回答:1
\n

(enter)仍然保留在缓冲区中,然后在while循环中以第一个

getchar()
读,这在缓冲区中没有任何东西要在第二个
getchar()
中读取,但仍然以某种方式进入循环,“嗯,那是6吗?”执行,我不明白如何。我将代码修复了我写的目的,但我仍然想知道是什么原因导致了这个确切的问题。
编码:

#include <stdio.h> int main() { int guess = 1; char c; printf("The program guesses the number between 1 and 100.\n"); printf("Respond it with Y if the guess is correct and N if the guess is wrong.\n"); printf("is your number %d?\n", guess); while((c = getchar()) != 'Y' || (c = getchar()) != 'y') { printf("well, is it %d then?\n", ++guess); if((c = getchar()) == '\n') continue; } printf("I knew it was %d", guess); return 0; }

输出:
The program guesses the number between 1 and 100.
Respond with Y if the guess is correct and N if the guess is wrong.
Is your number 1?
n
Well, is it 2 then?
n
Well, is it 3 then?
n
Well, is it 4 then?
nn
Well, is it 5 then?
Well, is it 6 then?
n
Well, is it 7 then?

I期望WARE循环终止,提示最后一份
printf()
最终导致该程序结束,而是随着此输出而结束。

The program guesses the number between 1 and 100. Respond it with Y if the guess is correct and N if the guess is wrong. is your number 1? n well, is it 2 then? n well, is it 3 then? n well, is it 4 then? nn well, is it 5 then?

    

您有一个无尽的循环,因为所有字母并非“ y”或不是“ y”。
尝试寻找不是“ y”而不是“ y”的字母。
如果您改变了您选择打电话两次的问题,例如您必须两次输入“ N”才能获得任何反馈。
c while-loop buffer getchar
1个回答
0
投票
我建议在循环结束时进行阅读和检查。 to做到这一点,我建议从

getchar()
切换到

while

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.