C中的While循环
谁能解释一下为什么当我输入字符“Q”时,我的while循环不会结束?它继续循环,即使当用户输入'Q'时,我将布尔值设置为false,它应该在C中的While循环,c,while-loop,C,While Loop,谁能解释一下为什么当我输入字符“Q”时,我的while循环不会结束?它继续循环,即使当用户输入'Q'时,我将布尔值设置为false,它应该在字符输入的scanf之后结束 我的代码: #include <stdio.h> typedef int bool; #define true 1 #define false 0 int main(void) { char input; char output; bool tf = true; printf("W
字符输入的scanf之后结束
我的代码:
#include <stdio.h>
typedef int bool;
#define true 1
#define false 0
int main(void) {
char input;
char output;
bool tf = true;
printf("Welcome to the Coder!\n");
while (tf) {
printf("Choose Input (H,A,B,Q) : ");
scanf_s(" %c\n", &input);
if (input == 'Q') {
tf = false;
}
else {
printf("Choose Output (H,A,B) : ");
scanf_s(" %c\n", &output);
}
}
return 0;
}
#包括
typedef int bool;
#定义真1
#定义false 0
内部主(空){
字符输入;
字符输出;
bool-tf=真;
printf(“欢迎使用编码器!\n”);
while(tf){
printf(“选择输入(H,A,B,Q):”;
扫描(“%c\n”,&input);
如果(输入='Q'){
tf=假;
}
否则{
printf(“选择输出(H,A,B):”;
扫描(“%c\n”、&output);
}
}
返回0;
}
我怀疑您正在控制台上输入小写字母q:
我建议您将代码更改为:
if (input == 'Q' || input == 'q') {
tf = false;
}
问题在于scanf\u s
的奇怪情况。根据,您可以使用以下语法读取单个字符:
scanf_s(" %c", &input, 1);
将\n
从scanf\u s
中删除,并添加1个参数,使其知道只能读取1个字符。如果
(input == 'Q' || input == 'q')
还有,为什么要添加typedef int bool代码>?这是不必要的
我将scanf_s
替换为scanf
,因为我的编译器无法识别它(意外地解决了问题)
因为它更好。当我编译这个时,没有错误
编译->您在键入Q后按enter键了吗?还有另一个scanf问题吗?是的,我确实按了enter键,因此,\include
和if(toupper(input)='Q')
。这解决了问题,谢谢。我真的不需要%c之后的\n