cLanguage Exception Occurred

Asked 1 years ago, Updated 1 years ago, 90 views

#include <stdio.h>

int main()
{
    int n1 = 0, n2 = 0;
    char c = 0;
    int val = 0;

    printf ("Enter an expression: ");
    scanf_s("%d%c%d", &n1, &c, &n2);

    switch (c)
    {
        case '+':
            val = n1 + n2;
            printf("%d + %d = %d", n1, n2, val);
            break;
        case '-':
            val = n1 - n2;
            printf("%d - %d = %d", n1, n2, val);
            break;
        case'*':
            val = n1 * n2;
            printf("%d * %d = %d", n1, n2, val);
            break;
        case'/':
            val = n1 / n2;
            printf("%d / %d = %d", n1, n2, val);
            break;
        default:
            printf ("Unable to calculate");
            break;
    }
    return 0;
}

I was making a simple calculator with c, and it says scanf_s ("%d%c%d", &n1, &c, &n2); exceptions occurred here. Can you tell me why? And I would appreciate it if you could tell me if I could reduce the code further here.

c exception calculator

2022-09-21 09:58

1 Answers

scanf_s() requires an additional buffer size (number of characters) for %c, %c, %s, %S.

Therefore, you need to create:

scanf_s("%d%c%d", &n1, &c, 1, &n2);


2022-09-21 09:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.