0

As the picture shows, it seems like the program does not recognize the characters entered by the user. I tried to make N as an array or initialized N = with those characters but it still won't work.

The code is:

#include <stdio.h>

int main()
{
    int a, b, c;
    char N;
    printf("Please enter a value for num 1 \n");
    scanf_s("%d", &a, sizeof(a));

    printf("Please enter a value for num 2 \n");
    scanf_s("%d", &b, sizeof(b));

    printf("Please enter a character \n");
    scanf_s("%s",&N, sizeof(N));

    switch (N)
    {
        case '+' : c = (a + b); printf("The sum is : %d \n", c); break;
        case '-' : c = (a - b); printf("The subtraction is : %d \n", c); break;
        case '*' : c = (a * b); printf("The muliplication is : %d \n", c); 
        break;
        case '/' : c = (a / b); printf("The division is : %d \n", c); break;
        default: printf("Please enter these characters only : + - * / \n"); 
    }

    getch();
    return 0;
}

default switch statement is chosen instead of others

SiggiSv
  • 1,219
  • 1
  • 10
  • 20

1 Answers1

2
scanf_s("%d", &a, sizeof(a));

Successfully read an integer and leaves a \n behind.

scanf_s("%d", &b, sizeof(b));

Happily ignores the newline, successfully reads an integer and leaves a newline behind.

scanf_s("%s",&N, sizeof(N));

Try to read a single non-whitespace, finds the newline, considers it a whitespace and fails. If you print the return value it probably is 0.

When the newline is handled (e.g. by reading and ignoring it) then the scanf_s will only succeed if you allow it to read the single character you want AND the null terminator, so you have to give at least 2*sizeof(char) as size.
Then of course you need to make N big enough to actually take two chars, being a single char, it currently is not.
Consider making it a char N[2];. I.e. with reading '+' like you attempt, you are actually trying to read "+" which is '+' and '\0'.

Alternatively use the "%c" format specifier and an additional " " before to ignore the leftover newline.
(More elegant and closer to your code, as supplied by Antti Haapala):

scanf_s(" %c", &N, 1);

Highly recommended:
Read the spec of the function you use and check the return value.

Help with dealing with this kind of hard to predict behaviour can be found:

http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ

Yunnosch
  • 26,130
  • 9
  • 42
  • 54