[英]Using getchar() when initial user input is "\n" C
使用 getchar() 方法为指定的用户输入设置字符值时,用户可能决定不输入任何内容,但仍按回车键。 有没有办法检查字符值是否为“\\n”?
// for example:
printf("input y/n\n");
char inp;
// the user hits enter before entering any value
inp = getchar();
getchar();
while (inp != 'y' && inp != 'n') {
inp = getchar();
getchar();
}
if (inp == 'y') {
printf("+\n");
} else {
printf("-\n");
}
示例输入/输出
情况1
'进入'
年
结果: +
案例2
'进入'
是
是
年
结果: +
案例3
'进入'
是
'进入'
是
结果: +
有人愿意解释这些情况吗? 作为一个刚接触 c 但对 java 比较有经验的人,我很想了解 getchar() 的用法和逻辑。
请删除第二个 getchar()
// the user hits enter before entering any value
inp = getchar();
//getchar(); // this getchar() is not needed
也在
while (inp != 'y' && inp != 'n') {
inp = getchar();
// getchar(); // this getchar() is not needed
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.