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
int days;-->int days = -1;scanf()which tells you how many conversions were successfully performed. You expect1, but if the input can't be parsed as a number, you will get0(and if there wasEOFor an error, you will getEOF). Always check the return value of functions that can return error indications!