-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

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 に答える