Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中执行While循环_C - Fatal编程技术网

在C中执行While循环

在C中执行While循环,c,C,我最近开始使用C编程语言,大约两三天前,但在使用do while循环时遇到了一些问题,这是我的程序中无法运行的部分 #include <stdio.h> #include <ctype.h> #include <stdbool.h> int main(void){ char another_game = 'Y'; scanf("%c", &another_game); do{ print

我最近开始使用C编程语言,大约两三天前,但在使用do while循环时遇到了一些问题,这是我的程序中无法运行的部分

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

int main(void){        
    char another_game   =   'Y';
    scanf("%c", &another_game);
    do{
        printf("\nWould you like to continue(Y/N)?");
        scanf("%c", &another_game);
    }while(toupper(another_game) == 'Y');
    return 0;
}
#包括
#包括
#包括
int main(void){
char另一个_游戏='Y';
scanf(“%c”和另一个_游戏);
做{
printf(“\N是否继续(是/否)”;
scanf(“%c”和另一个_游戏);
}while(toupper(另一个游戏)='Y');
返回0;
}

只要用户在提示时键入
'Y'
'Y'
,循环就会继续运行,但我注意到,在程序第一次执行循环后,它只是再次显示问题,然后循环中断。我尝试使用整数,当用户希望继续时,输入
1
,或者当用户希望退出时,输入
0
,这是有效的,所以我不理解为什么这个不能。我将非常感谢您对解决此问题的所有帮助,谢谢,因为当您按
时,stdin缓冲区中有尾随的换行符。最好改用
fgets()

char buf[0x10];
fgets(buf, sizeof(buf), stdin);
if (toupper(buf[0]) == 'Y') {
    // etc.
}

我会使用getchar,因为它对于您的目的更具确定性。还要确保再添加一个getchar来检查换行符

do{
printf(“输入Y/N\N”);
}而(((toupper(getchar())='Y')+(getchar()=='\n'))==2);

scanf(“%c”,…)
不使用换行符。你的确认得到了那条新线。使用
scanf(“%c”和另一个游戏)
跳过初始空白。(多次重复,但我懒得搜索。有人接受吗?)可能重复@robmayoff,对不起,我不是问为什么scanf不工作,我是问为什么我的程序不工作。谢谢您在扫描后使用flushall();参考[link]@jamesokpegorge的标题是错误的(如此多次如此)。这个问题是个骗局。谢谢,它奏效了,但我如何从scanf中消除尾随行,我的意思是如果有办法消除尾随行it@JamesOkpeGeorge我认为Daniel Fischer的评论总结了这一点,但您确实应该避免使用
scanf()
。它的用法不太直观,而且很容易出错,特别是对于初学者。我也不用它。我担心。