-2
void main()
{
  char day[20];
  printf("Enter the short name of day");

  scanf("%s", day);

  switch(day)
  {
    case "sun":
      printf("sunday");
      break;
    case "mon":
      printf("monday");
      break;
    case "Tue":
      printf("Tuesday");
      break;
    case "wed":
      printf("wednesday");
      break;
    case "Thu":
      printf("Thursday");
      break;
    case "Fri":
      printf("friday");
      break;
    case "sat":
      printf("saturday");
      break;
  }
}

This is my code. I got an error in switch case part.switch case not checking these cases. pls help me. thanks in advance.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Dhilip Kumar
  • 29
  • 1
  • 2
  • 6

4 Answers4

5

Using c, the only way I'm aware of is:

if (strcmp(day, "sun") == 0) 
{
   printf("sunday");
} 
else if (strcmp(day, "mon") == 0)
{
   printf("monday");
}
/* more else if clauses */
else /* default: */
{
}
sara
  • 3,824
  • 9
  • 43
  • 71
2

As mentioned, the switch statement won't work with strings in C. You can do something like this to make the code more concise:

#include <stdio.h>

static struct day {
  const char *abbrev;
  const char *name;
} days[] = {
  { "sun", "sunday"    },
  { "mon", "monday"    },
  { "tue", "tuesday"   },
  { "wed", "wednesday" },
  { "thu", "thursday"  },
  { "fri", "friday"    },
  { "sat", "saturday"  },
};

int main()
{
  int i;
  char day[20];
  printf("Enter the short name of day");

  scanf("%s", day);

  for (i = 0; i < sizeof(days) / sizeof(days[0]); i++) {
    if (strcasecmp(day, days[i].abbrev) == 0) {
      printf("%s\n", days[i].name);
      break;
    }
  }

  return 0;
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
0

This should work.
(but ONLY on strings that are 4-bytes or less)

This treats the strings as 4-byte integers.

This is considered, ugly, "hacky", and not at all good style.
But it does do what you wanted.

#include "Winsock2.h"
#pragma comment(lib,"ws2_32.lib")

void main()
{
  char day[20];
  printf("Enter the short name of day");

  scanf("%s", day);

  switch(htonl(*((unsigned long*)day)))
  {
    case 'sun\0':
      printf("sunday");
      break;
    case 'mon\0':
      printf("monday");
      break;
    case 'Tue\0':
      printf("Tuesday");
      break;
    case 'wed\0':
      printf("wednesday");
      break;
    case 'Thu\0':
      printf("Thursday");
      break;
    case 'Fri\0':
      printf("friday");
      break;
    case 'sat\0':
      printf("saturday");
      break;
  }
}

tested in MSVC2010

abelenky
  • 63,815
  • 23
  • 109
  • 159
-1

Look up the string in a const list. If found, use the index to switch.

An enum daysOfWeek { EwdMon,EwdTues,EwdWed....}; is a good place to start.

P0W
  • 46,614
  • 9
  • 72
  • 119
Martin James
  • 24,453
  • 3
  • 36
  • 60