Integer prints out as 0 in C when putting 1 in

Viewed 63

I think this is a really stupid question. I just started with C and made this little "calculator":

#include <stdio.h>
#include <stdlib.h>

int main() {
    while(1) {
        int a;
        int b;
        char op;
        printf("Enter the first number: ");
        scanf("%d", &a);
        printf("Enter the second number: ");
        scanf("%d", &b);
        printf("Enter the operator: ");
        scanf("%s", &op);

        switch(op) {
            case '+':
                printf("%d + %d = %d", a, b, a + b);
                break;
            case '-':
                printf("%d - %d = %d", a, b, a - b);
                break;
            case '*':
                printf("%d * %d = %d", a, b, a * b);
                break;
            case '/':
                printf("%d / %d = %d", a, b, a / b);
        }
        printf("\n");

        char cont;
        printf("Do you want to continue? (y/n): ");
        scanf("%s", &cont);

        if(cont == 'n') {
            break;
        }
    }
    return 0;
}

But when I run it and try to put in "1" and "1" it puts out the wrong number:

Enter the first number: 1
Enter the second number: 1
Enter the operator: +
1 + 0 = 1
Do you want to continue? (y/n): n

This is probably some dumb problem but I don't get it xD

1 Answers

You're reading the operator as a string, yet 'op' is a single char.

As a result, the terminating '\0' is written to the next byte in memory, which in this case is the first byte of the variable 'b' ('b' and 'op' are both on the stack).

As a fix I would suggest:

  • make 'op' a char array of size 2
  • use fgets to ensure that only 1 byte is read

char op[2] = {0};

fgets(op,2,stdin);

Related