我试过下面的代码,在输入字符之前需要 %d。那是代码中的 after switch 循环。
#include<stdio.h>
#include<conio.h>
void sum();
void mul();
void main()
{
char ch;
int c;
clrscr();
do
{
printf("\n\n Enetr choice ");
printf("\n\n\t 1: SUM \n\n\t 2: MUL");
scanf("\n\n\t %d",&c);
switch(c)
{
case 1:
sum();
break;
case 2:
mul();
break;
default:
printf("\n\n hhhh..... ");
}
printf("\n\n Want u calcualte again");
//scanf("%d");
scanf("%c",&ch);
printf("\n ch value is %c",ch);
}while(ch=='y'|| ch=='Y');
getch();
}
void sum()
{
int s;
s=10+50;
printf(" SUM: %d",s);
}
void mul()
{
int s;
s=10*50;
printf(" SUM: %d",s);
}
在切换后的这段代码中,我尝试输入字符,但在输入字符时没有注释中的 scanf 语句是必需的。没有那个 scanf 语句,编译器不会接受字符输入。所以请给我解决方案。
最佳答案
这是因为你必须“吃掉”之前输入的换行符
您不必使用 %d
。
改为使用:
while((c = getchar()) != '\n' && c != EOF) ;
代替
//scanf("%d");
丢弃换行符。
关于c - 为什么在输入字符之前需要 %d?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18425879/