C程序int变量值在读取字符值后发生更改

  • 本文关键字:字符 int 程序 变量值 读取 c
  • 更新时间 :
  • 英文 :


我是C编程的新手,我刚刚创建了一个小型计算器应用程序,但我注意到,当我在读取Int值后读取一个char值时,下一个直接的Int变量会发生变化。发生这种情况的原因是什么?这是我的代码

#include <stdio.h>
int main(){   
int num1;
int num2;
char opr;
int ans;
printf("Enter the first number : ");
scanf("%d", &num1);
printf("Enter the second number : ");
scanf("%d", &num2);
printf("Enter the operater : ");
scanf("%s", &opr);
printf("%d n", num1);
printf("%d n", num2);
switch(opr) {
case '+':
ans=num1+num2;
printf("The addtion of %d and %d is %d", num1, num2, ans);
printf("n");
break;
case '-':
ans=num1-num2;
printf("The substractuon of %d from %d is %d", num2, num1, ans);
printf("n");
break;
case '*':
ans=num1*num2;
printf("The multiplication of %d and %d is %d", num1, num2, ans);
printf("n");
break;
case '/':
ans=num1/num2;
printf("The substraction of %d from %d is %d", num1, num2, ans);
printf("n");
break;
}
return 0;
}

这里您必须使用scanf("%c", &opr);而不是scanf("%s", &opr);。由于oprchar,您必须使用%c%s用于扫描字符串。然后出现未处理的'n'问题。所以在%c的前面加一个额外的'n'。因此,该语句变为scanf("n%c", &opr);

修改代码:-

#include <stdio.h>
int main()
{
int num1;
int num2;
char opr;
int ans;
printf("Enter the first number : ");
scanf("%d", &num1);
printf("Enter the second number : ");
scanf("%d", &num2);
printf("Enter the operater : ");
scanf("n%c", &opr); // not scanf("%s", &opr);
printf("%d n", num1);
printf("%d n", num2);
switch (opr)
{
case '+':
ans = num1 + num2;
printf("The addtion of %d and %d is %d", num1, num2, ans);
printf("n");
break;
case '-':
ans = num1 - num2;
printf("The substractuon of %d from %d is %d", num2, num1, ans);
printf("n");
break;
case '*':
ans = num1 * num2;
printf("The multiplication of %d and %d is %d", num1, num2, ans);
printf("n");
break;
case '/':
ans = num1 / num2;
printf("The substraction of %d from %d is %d", num1, num2, ans);
printf("n");
break;
}
return 0;
}

输出:-

Enter the first number : 3
Enter the second number : 4
Enter the operater : *
3 
4 
The multiplication of 3 and 4 is 12

使用scanf("%c", &opr)读取单个char

使用%s将读取以NUL结尾的字符串,但您只有一个字节,这是不够的,从而导致未定义的行为。

实际发生的情况是,NUL终止符被写在opr旁边的int变量的顶部一个字节上。

如其他人所述,使用%c:读取字符

但是您使用了%s,所以发生的是scanf读取一个字符串。假设您的示例的正常输入将读取一个字符和一个换行符。然后,Scanf写入字符和一个0字节的终止地址,该地址就是您的字符。

但一个字符只有一个字节大,另一个溢出到内存中的下一个字符上。在您的情况下,这恰好是int变量。这被称为缓冲区溢出,也是使用scanf的危险之一。

最新更新