-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.

4

4 回答 4

5

使用 c,我知道的唯一方法是:

if (strcmp(day, "sun") == 0) 
{
   printf("sunday");
} 
else if (strcmp(day, "mon") == 0)
{
   printf("monday");
}
/* more else if clauses */
else /* default: */
{
}
于 2013-09-03T11:35:59.797 回答
2

如前所述,该switch语句不适用于 C 中的字符串。您可以执行以下操作以使代码更简洁:

#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;
}
于 2013-09-03T11:41:53.293 回答
0

这应该有效。
(但仅适用于 4 字节或更少的字符串)

这将字符串视为 4 字节整数。

这被认为是丑陋的,“hacky”,而且根本不是好的风格。
但它确实做你想做的事。

#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;
  }
}

在 MSVC2010 中测试

于 2013-09-03T11:40:14.640 回答
-1

在 const 列表中查找字符串。如果找到,使用索引进行切换。

Anenum daysOfWeek { EwdMon,EwdTues,EwdWed....};是一个很好的起点。

于 2013-09-03T11:41:06.370 回答