在循环比较CHAR [英] Comparing char in a while loop
问题描述
只要输入不是X,循环将继续要求输入并打印出A或B。
INT主要(无效){ 字符输入; 而(输入!='X'){ 的printf(请输入输入:); scanf函数(%C,&安培;输入); 如果(输入=='一'){ 的printf(A \\ n);
} 其他{ 的printf(B \\ n);
} } 返回(0);
}
问题是后,我进入了输入端,每次,它打印输出,同时也打印出输入输入:B在新线无论我进入a或b或其他任何东西作为输入。谁能告诉我,我怎么能解决这个问题,谢谢!
下面是发生了什么:
输入输入:一个
A
输入输入:B /的后的输出总是打印此行,怎么
我可以摆脱它? /
输入输入:一个
A
输入输入:乙
输入输入:乙
乙
输入输入:乙
输入输入:乙
块引用>解决方案为了忽略换行符,在
scanf函数
应该有可能是:scanf函数(%C,&安培;输入);
^此外,你可能想后刷新标准输出正确的
的printf
:的printf(请输入输入:);
fflush(标准输出);As long as the input is not x, the loop will continue to ask for the input and it prints out either A or 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); }
The problem is that everytime after i entered the input, it prints the output and it also prints out "Enter Input:B" in a new line no matter i entered a or b or anything else as input. Can anyone tell me how can i solve this problem, Thanks!
Here is what happened:
Enter Input:a
A
Enter Input:B /after the output it always prints this line, how can i get rid of it??/
Enter Input:a
A
Enter Input:B
Enter Input:b
B
Enter Input:B
Enter Input:b
解决方案In order to ignore newlines, the
scanf
should likely be:scanf(" %c", &input); ^
Also you probably want to flush stdout right after that
printf
:printf("Enter Input:"); fflush(stdout);
这篇关于在循环比较CHAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!