integer input in switch case and user enter strings

时间:2017-08-05 12:11:41

标签: c switch-statement

I am writing code for my switch case. I am taking input from the user and printing the respective day based on the input. But my question is, if user is giving string input it is printing case 0 statement as output. Can anyone please correct this program?

#include<stdio.h>

int main(void){
    int  days;
    scanf("%d",&days);

    switch(days){
        case 0: printf("Mon");break;
        case 1: printf("Tue");break;
        case 2: printf("Wed");break;
        case 3: printf("Thu");break;
        case 4: printf("Fri");break;
        case 5: printf("Sat");break;
        case 6: printf("Sun");break;
        default: printf("Plz enter a valid day(0-6) :( ");
    }
    return 0;
}

My output printing is :

>>a.out
  Naveen
  mon

2 个答案:

答案 0 :(得分:3)

scanf won't modify your int if the format specifier isn't found in the input.

In this case, you're switching on an uninitialized int. Doing anything with uninitialized POD types is generally A Bad Thing™, so you should take care that your value is initialized properly.

In this case, since you want it to trigger the default branch, initializing as int days = -1; (or as anything not in [0,6]) should do the trick.

PS: Note that scanf also returns an int telling you how many arguments it successfully found. This means you can check if scanf returned either 0 or EOF and handle this case separately - for example a more descriptive error message.

答案 1 :(得分:0)

loop until days was properly scanned

 while(scanf("%d",&days) != 1) getc(stdin);
相关问题