scanf(“%C”,& opt)和scanf(“%C”,& opt)之间的差异
问题描述:
我在IDE TurboC3中执行我的c语言程序。
非工作代码如下
I am executing my c language program in IDE TurboC3.
Non working code is as follows
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, t;
char opt;
clrscr();
printf("Enter two values" );
scanf("%d", &i);
scanf("%d", &j);
printf("\n\n press + for sum\n");
printf("press * for mult\n");
printf("print - for subtract\n\n");
scanf("%c", &opt); // code that is creating problem //
switch(opt)
{
case '+':
{t=i+j;
printf("\nsum =%d", t);
}
break;
case '*':
{t=i*j;
printf("\nproduct =%d", t);
}
break;
case '-':
{t=i-j;
printf("\ndifference =%d", t);
}
break;
default:
printf("\ninvalid choice");
}
getch();
}
代码块已更正,缩进添加 - OriginalGriff [/ edit]
我尝试了什么:
帮助我执行代码的更正如下
[edit]Code block corrected, indentation added - OriginalGriff[/edit]
What I have tried:
The correction that helped me execute the code is as follows
scanf(" %c", &opt); // code without problem //
即我在和%c之间插入了一个空格和代码工作。
请帮我理解其中的区别。
i.e. i have inserted a space between " and %c and the code worked.
Please help me understand the difference.
答
不同之处在于scanf按字面意思使用格式字符串:对空格的需要意味着您的输入不是+,而是在它之前有空格。%c是一个scanf特殊代码:它根本不会跳过空格字符(不像%d那样)。所以当你的用户输入这两个值时,终结符可能留在缓冲区中并作为第一个字符返回而不是用户键入的'*'或'+'。
说实话,你可能最好使用getch和循环,特定的退出字符,而不是读取一个字符并停止。
个人?我会在单独的行中提示每个号码,将其读作char数组,并将其扫描成一个数字 - 这样我就可以应对用户输入错误而不是像你的代码那样崩溃。然后我会为运营商使用getch。
The difference is that scanf uses the format string literally: the need for a space implies that your input is not '+' but has whitespace before it. "%c" is a scanf "special" code: it does not skip whitespace characters at all (unlike "%d" which does). So when your user entered the two values, the terminator was probably "left in the buffer" and returned as the first character instead of the '*' or '+' that the user typed.
To be honest, you'd probably be better off using getch and a loop, with a specific "exit" character instead of reading one char and stopping.
Personally? I'd prompt for each number on a separate line, read it as a char array, and scan that into a number - that way I could cope with user input errors instead of crashing as your code will. Then I'd use getch for the operator.