0

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
  • 1
    int days; --> int days = -1; Commented Aug 5, 2017 at 12:13
  • 7
    For example what @BLUEPIXY said, but I'd recommend to use the return value of scanf() which tells you how many conversions were successfully performed. You expect 1, but if the input can't be parsed as a number, you will get 0 (and if there was EOF or an error, you will get EOF). Always check the return value of functions that can return error indications! Commented Aug 5, 2017 at 12:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

loop until days was properly scanned

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.