在while循环中比较char
只要输入不是x,循环就会继续询问输入,并打印出A或B.
int main (void){ char input; while( input != 'x'){ printf("Enter Input:"); scanf("%c", &input); if (input == 'a'){ printf("A \n"); } else{ printf("B\n"); } } return (0); }
问题是,每次输入输入后,它都会输出输出,并且无论输入a还是b或其他任何内容作为输入,它都会在新行中打印出“输入输入:B”。 谁能告诉我怎样才能解决这个问题,谢谢!
这是发生的事情:
输入输入:a
一个
输入输入:B / 输出后它总是打印这一行,我怎么能摆脱它? /
输入输入:a
一个
输入输入:B
输入输入:b
乙
输入输入:B
输入输入:b
为了忽略换行符, scanf
可能应该是:
scanf(" %c", &input); ^
你也许想在printf
之后立即刷新stdout:
printf("Enter Input:"); fflush(stdout);
你需要吃newline
:
scanf("%c", &input); while((ch=getchar())!='\n');
该错误是因为从输入读取换行符。
你也可以参考这个: 为什么getchar()不等我在scanf()后按Enter键?