6

I am a beginner and I am learning C and C++. I am trying to run this code in Visual Studio 2012 Express for Windows Desktop. This is a simple calculator code which I have written by myself! But whenever I run it I get this error Unhandled exception at 0x519600B4 (msvcr110d.dll) in Calculator.exe: 0xC0000005: Access violation writing location 0x00000000.

Forgive me for any mistakes (it is my first time). Thank you!

#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();
}
4

1 回答 1

15

使用时scanf_s,对于%c格式字符串,您必须指定要读取的字符数:

scanf_s("%d%c%d", &num1, &oper, 1, &num2);

文档描述了要求:

与 scanf 和 wscanf 不同,scanf_s 和 wscanf_s 需要为类型 c、C、s、S 或包含在 [] 中的字符串控制集的所有输入参数指定缓冲区大小。以字符为单位的缓冲区大小作为附加参数传递,紧跟在指向缓冲区或变量的指针之后。

于 2013-06-13T08:35:03.573 回答