I am writing a c program to print specific statements if current day is Friday using if-else statement. What is the error involved?
I've tried using integer values for the same code and it works, but when i equate n as Friday the output shows else part only.
char s[10]="Friday";
char n[6];
printf("Enter a day:\n");
scanf("%s",n); //n is string
if(n==s)
printf("Have a nice weekend!");
else
printf("Have a nice day!");
I expect the output for "Friday" to be "Have a nice weekend!", but the output is "Have a nice day!" for any input.
You should use a function like strcmp to compare char arrays in C
.
if(strcmp(s, n) == 0) {
printf("Have a nice weekend!");
}
When you use the ==
operator you are comparing addresses (or sometimes pointers), not string literal values.
Also as pointed out above (pun intended) an array in C
needs space for the null terminating character.