Shubham Mishra
Shubham Mishra

Reputation: 1

if statement not taking input in strcmp string input

#include <stdio.h>
#include <conio.h>
#include <string.h>

main() {
    char d[10];
    int value = 0, val1, val2;
    printf("Enter Day: ");
    scanf("%c", &d);

    val1 = strcmp(d, "sunday");
    val2 = strcmp(d, "saturday");
    
    if (val1 == 0) {
        printf("AS");
        value = 2;  
    } else
    if (val2 == 0) {
        value = 1;   
    } 
       
    switch (value) {
      case 2:
        printf("So sad, you will have to work");
        break;
      case 1:
        printf("Enjoy! its holiday");
        break;
      default:
        printf("Print valid character");
    }
}

I enter code here want to input days and to get some output using switch statement but strcmp is not working in if statement I have to use a switch statement also if statement not recognising value.

Upvotes: 0

Views: 112

Answers (1)

chux
chux

Reputation: 153338

At least this problem:

strcmp(d,"sunday") expects array d to contain a string.

d does not certainly contain a string as no null character was assigned there.

char d[10];
printf("Enter Day: ");
scanf("%c",&d);  // Writes, at most, 1 character to `d`. Remainder of `d[]` is uninitialized.

Instead

if (scanf("%9s",d) == 1) {
  printf("Success, read <%s>\n", d);

Tip: Consider using fgets() to read user input.

Tip: Enable all compiler warnings to save time.

Upvotes: 2

Related Questions