Zokeh Zokeh - 11 months ago 51
C Question

In C can I print the number of the an enum while input is a string/char, using enumeration?

I'm trying to make a code that lets the user input a weekday (i.e monday), and then making it print which number the day is in the week.

#include <stdio.h>

enum week {monday, tuesday, wednesday, thursday, friday, saturday, sunday};

int main (void) {

enum week day;

printf("Enter weekday:\n");
scanf(%c, &day);

printf("It is day number %d in the week, day+1"); // Enumeration is 0-indexed, which is why day+1 is added so that the 1st day is monday, otherwise monday would be the 0th day


This is what I came up with so far - can I do it like this?

Answer Source
// scanf(%c, &day);
scanf("%c", &day);

Only reads 1 character into day.

Suggest adding an array of week day names.

Input a string.
Lop off trailing \n
Convert to lower case if desired. (not shown)
Test input against the 7 names.
Report results.

int main(void) {
  enum week {
    monday, tuesday, wednesday, thursday, friday, saturday, sunday

  static const char *weekday_name[sunday - monday + 1] = { "monday", "tuesday",
      "wednesday", "thursday", "friday", "saturday", "sunday" };

  printf("Enter weekday:\n");
  char buffer[80];
  fgets(buffer, sizeof buffer, stdin);
  buffer[strcspn(buffer, "\r\n")] = 0; // lop off trailing \r and/or \n

  enum week wdn;
  for (wdn = monday; wdn <= sunday; wdn++) {
    if (strcmp(weekday_name[wdn], buffer) == 0) {
  if (wdn > sunday) puts("Day not found");
  else printf("It is day number %d in the week\n", wdn);