-1

I want to save typedef enum date to typedef struct data.

My code is

typedef enum weather {
    clear = 1,
    cloudy,
    cold,
    rainy,
    stormy
}Weather;



typedef struct diary {
    time_t date;
    Weather weather;
    char contents[MAX];
}Diary;

void save(FILE *pFile, Diary*da) {

    fprintf(pFile, " %s %s \n",da->date,da->contents);
}


void in(Diary*da) {
    int _weather;

    puts("Enter the current date(YYYY-MM-DD) : ");
    scanf("%s", &da->date);
    getchar();

    puts("Enter the current weather, (1) Clear (2) Cloudy (3) Cold (4) Rainy (5) Stormy : ");
    scanf("%d", &_weather);
    getchar();

    puts("Enter the contents");
    scanf("%79s", da->contents);
    getchar();

}

I don't know how to change the number to words(clear, cloudy, cold..) and print out in output file.

And what exactly 'time_t' data type? I can't printout the date that I entered.

  • 1
    "how to change the number to words". `switch (_weather)`? That's a basic way. A smarter way would be to have an array of strings with the index derived from the input number (ie a lookup table). – kaylum Nov 30 '16 at 01:01
  • All your questions are described in your C book. It is not clear what your **specific** problem is. Read [ask] and follow the advice. And names starting with an underscore are reserved for the implementation. Don't use them. – too honest for this site Nov 30 '16 at 01:02
  • And try searching (it's free). [How to print time_t in a specific format?](http://stackoverflow.com/questions/18422384/how-to-print-time-t-in-a-specific-format) – kaylum Nov 30 '16 at 01:04
  • You might want to look up 'designated initializers' and 'x-macros' (there is documentation in Documentation on X-Macros, though there is room for improvement there). – Jonathan Leffler Nov 30 '16 at 03:07

1 Answers1

2

Kaylum mentioned this in the comment under your post, this is what was being suggested:

const char* const WEATHER_STRINGS[5] = { "Clear", "Cloudy", "Cold", "Rainy", "Stormy" };

const char* getWeatherName(int weatherIdx)
{
   return WEATHER_STRINGS[weatherIdx];
}

Then you can call the function like this:

getWeatherName(&da->weather)

Which will return the word matching the integer value of the enum.

My c may be a tad rusty, but the idea is sound, just verify my syntax. =)

The idea is that you create an array to use as a lookup for your strings/values. Then you can use your enum as the index to pull the matching word from the array. You don't need the function, you could pull directly from the array if you wanted to, but encapsulating it with a function makes it a bit more readable and then you can always expand it if you need more functionality later.

As for time_t, you can take a look at a previously answered question for more information regarding it: How to print time_t in a specific format?

Community
  • 1
  • 1
gmiley
  • 6,531
  • 1
  • 13
  • 25