user3449151
user3449151

Reputation: 21

Convert Month Name into Number C++

I haven't touched C++ in a very long time and I'm sure this can be done in a one liner.

I have a string day that I want to convert into a value between 0-11. I'd usually do something like this

months = array('Jan', 'Feb', 'Mar', 'Apr' ...);
print months[day];

But I have no idea how to do that in C++

Upvotes: 1

Views: 16042

Answers (4)

j-hap
j-hap

Reputation: 333

I know this is a very old question, but I'd like to add: You can put the string with the abbreviated month in a stringstream and use

int main() {
  std::string s = "Feb";
  std::stringstream ss(s);
  std::tm result;
  ss >> std::get_time(&result, "%b");
  std::cout << result.tm_mon << "\n";
  return 0;
}

This takes the locale into account and can be adopted for different languages by imbueing the locale to the stringstream.

Upvotes: 0

Victor
Victor

Reputation: 14593

A simple approach would be something like this:

vector<string> months = { "jan", "feb", "mar", "apr", "may", ... };
int month_number = 2;

cout << months[ month_number - 1 ] // it is month_number-1 because the array subscription is 0 based index.

A better, but more complex and advanced approach is to use std::map like below:

int get_month_index( string name )
{
    map<string, int> months
    {
        { "jan", 1 },
        { "feb", 2 },
        { "mar", 3 },
        { "apr", 4 },
        { "may", 5 },
        { "jun", 6 },
        { "jul", 7 },
        { "aug", 8 },
        { "sep", 9 },
        { "oct", 10 },
        { "nov", 11 },
        { "dec", 12 }
    };

    const auto iter = months.find( name );

    if( iter != months.cend() )
        return iter->second;
    return -1;
}

Upvotes: 6

Spire
Spire

Reputation: 685

You can use a std::map to write a function like this:

int GetMonthIndex(const std::string & monthName)
{
    static const std::map<std::string, int> months
    {
        { "Jan", 0 },
        { "Feb", 1 },
        { "Mar", 2 },
        { "Apr", 3 },
        { "May", 4 },
        { "Jun", 5 },
        { "Jul", 6 },
        { "Aug", 7 },
        { "Sep", 8 },
        { "Oct", 9 },
        { "Nov", 10 },
        { "Dec", 11 }
    };

    const auto iter(months.find(monthName));

    return (iter != std::cend(months)) ? iter->second : -1;
}

Upvotes: 4

Carmine Ingaldi
Carmine Ingaldi

Reputation: 976

you can use a simple switch, or a std::map , this is less verbose

Upvotes: -2

Related Questions