Reputation: 19
I have written a program that outputs the maximum and minimum number of days frost was recorded along with the corresponding year and month. I am reading this data from a file and inputting what i need into vectors.
In the file the months are displayed in integers 1-12, My question is that in my program when outputting the month, how can I output "January" when in the the file it's a 1?
Upvotes: 0
Views: 286
Reputation: 57688
If your compiler doesn't support std::array
, you can use a fixed array of characters:
static const char * month_names[] =
{
"Dummy", // to make names line up with month numbers.
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December",
};
int main(void)
{
for (unsigned int m = 1; m <= 12; ++m)
{
cout << m << ") " << month_names[i] << endl;
}
return EXIT_SUCCESS;
}
Note: The type char *
is used for the array since char *
can be stored as fixed data and accessed directly. Using std::string
would involve creating a std::string
instance for each month name before accessing them.
Upvotes: 0
Reputation: 117866
You can make a std::array
of std::string
. The index will correspond to the month name. Just make sure you account for 0-based indexing, e.g. "January" == 0
, not 1
.
std::array<std::string, 12> months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
Then
cout << "The highest number of days frost was recorded is: "
<< maxFrost
<< ". The date was: "
<< months[maxMonth - 1] // adjust to 0-based index
<< ", "
<< maxFyear
<< ".\n"
<<endl; // maximum frost with month and year
Upvotes: 2