【发布时间】:2017-12-09 11:51:10
【问题描述】:
Dev-c++有两段代码,第一段正常,另一段不行,为什么??
/* this code is working properly*/
#include<stdio.h>
int main()
{
char op; // this is the point
int a,b,c; // where another code differs
printf("Enter the two no.s:");
scanf("%d %d",&a,&b);
printf("Enter the operation(+/-/*//):");
scanf("%s",&op);
switch(op)
{
case '+': c=a+b;
printf("%d",c);
break;
case '-': c=a-b;
printf("%d",c);
break;
case '*': c=a*b;
printf("%d",c);
break;
case '/': c=a/b;
printf("%d",c);
break;
default: printf("Invalid Operation");
}
}
/* this code is not working properly; only altered the declaration sequence of int and char*/
#include<stdio.h>
int main()
{
int a,b,c;
char op;
printf("Enter the a:");
scanf("%d %d",&a,&b);
printf("Enter the operation(+/-/*//):");
scanf("%s",&op);
switch(op)
{
case '+' : c=a+b;
printf("%d",c);
break;
case '-' : c=a-b;
printf("%d",c);
break;
case '*' : c=a*b;
printf("%d",c);
break;
case '/' : c=a/b;
printf("%d",c);
break;
default: printf("Invalid Operation");
}
}
【问题讨论】:
-
scanf("%s",&op);->op是一个单一的char,但您正在尝试读取字符串 -> 未定义的行为 -
无论如何 -
scanf("%s",&op)是 UB,因为op是char。两个 sn-ps 都坏了。 -
替换 %s-->%c
-
这是一个很好的例子,为什么它被称为“未定义的行为”而不是错误或崩溃或其他任何东西。环境(因此是随机的)上下文影响程序的行为方式。如您所见,这可能从“似乎表现正确”(一个极端)到崩溃(另一个极端)。介于两者之间的是更可怕的事情:“大多数时候行为正确”(偶尔出现的错误通常出现在客户端,但从未出现在调试器中)。原因已经被指出了两次:不幸的是(通常)C 编译器没有检测到
scanf()的错误用法。 -
scanf("%s",&op);->scanf(" %s",&op);。注意%c前面的空格。