我是初学者,正在学习 C 和 C++。我正在尝试在 Visual Studio 2012 Express for Windows Desktop 中运行此代码。这是我自己写的一个简单的计算器代码!但是每当我运行它时,我都会在 Calculator.exe 中收到此错误 Unhandled exception at 0x519600B4 (msvcr110d.dll): 0xC0000005: Access violation writing location 0x00000000.
如有错误请见谅(我是第一次)。谢谢!
#include<stdio.h>
#include<conio.h>
main ()
{
int num1, num2, result;
char oper;
scanf_s("%d%c%d", &num1, &oper, &num2);
switch(oper)
{
case '+':
result = num1 + num2;
printf("%d", result);
break;
case '-':
result = num1 - num2;
printf("%d", result);
break;
case '*':
result = num1 * num2;
printf("%d", result);
break;
case '/':
result = num1 / num2;
printf("%d", result);
break;
default:
printf("ERROR: INVALID OR UNRECOGNISED INPUT\n");
break;
}
_getch();
}
最佳答案
使用 scanf_s
时,对于 %c
格式字符串,您必须指定要读取的字符数:
scanf_s("%d%c%d", &num1, &oper, 1, &num2);
documentation描述要求:
Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.
关于c - 访问冲突错误 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17082604/