Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.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 无法完全执行do while循环_C_While Loop_Char_Scanf - Fatal编程技术网

C 无法完全执行do while循环

C 无法完全执行do while循环,c,while-loop,char,scanf,C,While Loop,Char,Scanf,我正在尝试使用do while执行一个小程序 #include<stdio.h> #include<conio.h> void main() { char another; int num; do { printf("Enter a number"); scanf("%d",&num); printf("Square of %d id %d",num,num*num); printf("Want to another another

我正在尝试使用
do while
执行一个小程序

#include<stdio.h>
#include<conio.h>
void main()
{
char another;
int num;
do
{
    printf("Enter a number");
    scanf("%d",&num);
    printf("Square of %d id %d",num,num*num);
    printf("Want to another another number y/n");
    scanf("%c",&another);
}while(another=='y');
}
#包括
#包括
void main()
{
互相指责;
int-num;
做
{
printf(“输入一个数字”);
scanf(“%d”和&num);
printf(“%d id%d的平方”,num,num*num);
printf(“想要另一个号码是/否”);
scanf(“%c”和另一个);
}而(另一个=='y');
}
现在,当我尝试执行程序时,它运行良好。我输入一个数字,它显示它的平方。然后我看到
想输入另一个数字y/n
。但只要我按任意键(y或n),程序就会在我按enter键提供输入之前自动退出。我试了很多次,但没有成功

但是如果我要求用户输入1或2(代替y/n),程序运行良好。在这种情况下,它接受整数输入并可以检查while块。如果
other==1
,程序将再次运行


我的问题是,为什么我不能在
while
条件下检查字符。

它不起作用的原因是
scanf
获取
num
后,新行仍在缓冲区中,因此它将由下一个
scanf
使用
%c
格式说明符处理。固定它的直接方法是使用:

scanf(" %c", &another);
//     ^space

请注意,您的原始
scanf(“%c:,&另一个”)
不会编译,但我认为这是一个输入错误。并且总是使用
int main
,或者它是未定义的行为。

它不起作用的原因是,在
scanf
获取
num
之后,新行仍然在缓冲区中,因此它将由下一个
scanf
使用
%c
格式说明符进行处理其固定方式如下:

scanf(" %c", &another);
//     ^space

请注意,您的原始
scanf(“%c:,&other”)不会编译,但我认为这是一个输入错误。始终使用
intmain
,否则这是未定义的行为。

谢谢兄弟。你真的帮了我很多。我受够了思考我的代码有什么问题。你救了我。但是你能解释一下为什么我在%c之前需要一个空格而在%d中不需要吗???@user2899258基本上这是因为新行字符是有效字符,但不是有效整数,所以
scanf
仅在格式说明符有
[
c
n
。在
%c
之前添加空格将使
scanf
忽略您需要的字符之前的任何空格。谢谢兄弟。您真的帮了我很多忙。我受够了思考我的代码有什么问题。您救了我。但您能解释一下为什么我需要在%c之前添加空格而不是nee吗因为新行字符是有效字符,但不是有效整数,所以
scanf
仅在格式说明符具有
[
c
n
。在
%c
之前添加空格将使
scanf
忽略所需字符之前的任何空格。