这是一个简单的C程序,解释do while loop.Before循环在那里结束两个scanf。/我真的把“scanf("%d",&dummy);”弄糊涂了。如果没有这一行,程序将不会按预期运行。因此,我认为这一行就像是某种占位符,用来创建一个空间来接受聊天输入。但我不确定这一点,以及它是如何实际工作的
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice,dummy;
do{
printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello");
break;
case 2:
printf("Javatpoint");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy); //This part confuses me
scanf("%c",&c);
}while(c=='y');
}
发布于 2020-07-31 11:07:41
因为变量dummy
被用来捕获选项数字后面的return
。
如果我们添加一行来打印虚拟对象
printf("[%c]\n", dummy); // We should change dummy's type to char, omit here
这是对结果的解释:
1. Print Hello
2. Print Javatpoint
3. Exit
1 # This is input: 1 and an invisible return
Hellodo you want to enter more?[ # return is captured by scanf and printed
]
y # This is input: y and an invisible return, return is ignored by scanf("%d", &choice), because it need numbers
1. Print Hello
2. Print Javatpoint
3. Exit
2 # This is input: n and an invisible return
Javatpointdo you want to enter more?[
]
n
发布于 2020-07-31 11:57:31
这是因为scanf留下了一个'\n‘字符,如果使用了%c,则下一次scanf读取该字符。
解决方案:将报告的程序中的%c替换为%1s以解决此问题(要读取下一个非空白字符,请使用%1s而不是%c)。
请参考下面的程序,查看由于换行符出现的问题。
root@localhost Programs# cat -n scan.c
#include<stdio.h>
#include<stdlib.h>
int main ()
{
char c = 0;
int choice,dummy;
do{
printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello\n");
break;
case 2:
printf("Javatpoint\n");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice\n");
}
printf("say 'y' if you want to enter more\n");
scanf("%c",&c);
printf("%d\n",c);
scanf("%c",&c);
printf("%d\n",c);
}while(c=='y');
return 0;
}
您可以看到值10,它是前面scanf留下的字符'\n‘的值。
#include
#include
int main ()
{
字符c= 0;
int choice,哑巴;
执行{
printf("\n1.打印Hello\n2.打印Javatpoint\n3.退出\n“);
scanf("%d",&choice);
开关(选项)
{
案例1:
printf("Hello\n");
中断;
案例2:
printf("Javatpoint\n");
中断;
案例3:
退出(0);
中断;
默认值:
printf(“请输入有效选项\n”);
}
printf(“如果您想输入更多,请说'y‘\n”);
scanf("%1s",&c);}while(c=='y');
返回0;}
https://stackoverflow.com/questions/63184980
复制相似问题