简体   繁体   中英

Switch statement is not working in C

Whenever user type 2 integers and choose anything from +,-,*,/,the program runs switch statement.The problem is switch statement makes the first integer 0 and gives the result based on that.

Let say 2 integers are 4 and 8.User choose + .Program gives result like this 0+8=8.Same for other options too.

Here is the code:

#include <stdio.h>

int main() {
    int x,y;
    char choice;

    printf("Enter the first Integer:\n");
    scanf("%d",&x);
    printf("Enter the second Integer:\n");
    scanf("%d",&y);

    printf("Choose the action you want to perform\n")
    scanf("%s",&choice);
    switch(choice) {
        case '+':
            printf("\n%d + %d = %d",x,y,x+y);
            break;

        case '-':
            printf("\n%d - %d = %d",x,y,x-y);
            break;

        case '*':
            printf("\n%d * %d = %d",x,y,x*y);
            break;  

        case '/':
            if(y==0) {
                printf("Undefined value\n");
            } else {
                printf("\n%d / %d = %d",x,y,x/y);
            }  
            break;

        default:
            printf("\n Enter something valid\n");
            break; 
    }

    return 0;
}

Need your help in this issue.

Since choice is a char (not a string) then:

scanf("%s",&choice);

should be

scanf(" %c",&choice);

Note the space before the %c - this is useful to flush any white space characters from the input buffer, eg a newline character from the previous input.

Note also that if you had enabled compiler warnings (eg gcc -Wall ... ) then the compiler would have pointed out this mistake to you immediately.

Your bug is this:

char choice;

scanf("%s",&choice);

%s references a string, but you only supply a pointer to a character. This causes your variables on the stack (in special "y") to be overwritten with the rest of the string. In case you just input one character, the first character is stored in 'choice' and the zero termination byte is overwriting some parts of variable "y" (next to it on the stack).

To fix this use a string of length 2, but LIMIT(!) the scanf to 1 character!. The switch must then test the first character of the string...

char choice[2];
[...]
scanf("%s",&choice);

switch(choice[0]) {
[...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM