Ç - 试图读取从标准输入一个字符(和失败)W / scanf函数/的getchar [英] C - trying to read a single char from stdin (and failing) w/ scanf / getchar
问题描述
作为家庭作业的一部分,我想从stdin读取一个单个字符,并采取行动根据它:
as a part of a homework assignment, I'm trying to read a single char from stdin, and act according to it:
char choice;
while (1) {
printf("please enter [y]es, [n]o or [m]aybe: ");
scanf("%c", choice);
fflush(stdin);
// validate input
if (choice == 'y' || choice == 'n' || choice == 'm') {
break;
} else {
printf("Please enter only \'y\', \'n\' or \'m\'!\n");
}
}
// do something with the input
if (choice == 'y') {
printf("you selected yes!\n");
}
由于某种原因,scanf的同时捕捉焦炭,换行之后,因此,它继续做与输入的东西,然后同时打印请输入只有'Y','n'或'M'!线。如果我在标准输入输入几个字符,将打印该行对所有的人,同时也是第一个字符的正确执行。因此,例如:
for some reason, scanf captures both the char and the line-feed after, thus it proceeds to do something with the input and then also prints the "Please enter only 'y', 'n' or 'm'!" line. If I enter several characters on the stdin, it will print that line for all of them, while also performing correctly for the first char. So, for example:
$ ./run
please enter [y]es, [n]o or [m]aybe: y<return>
you selected yes!
Please enter only 'y', 'n' or 'm'!
$ ./run
please enter [y]es, [n]o or [m]aybe: yes<return>
you selected yes!
Please enter only 'y', 'n' or 'm'!
Please enter only 'y', 'n' or 'm'!
Please enter only 'y', 'n' or 'm'!
$
如果我使用的getchar同样的事情发生。我在想什么?谢谢。
Same thing happens if I use getchar. What am I missing? thanks.
推荐答案
您需要scanf函数(和之间的空间
%C
为它正常工作:
You need a space between scanf("
and the %c
for it to work correctly:
scanf(" %c", &choice);
而且你还需要使用&安培;!选择,而不是选择
And you also need to use &choice, not choice!
编辑:当你在这,你可能想看看做的,而()
为循环(除非教授明确表示使用破
)! - 做的,而
验证用户输入时的伟大工程
While you're at it, you might want to look into do while()
for that loop (unless the professor specifically said to use a break
) - do while
works great when validating user input!
这篇关于Ç - 试图读取从标准输入一个字符(和失败)W / scanf函数/的getchar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!