How to map user input with enum value?

2019-03-07 17:43发布

I have a basic enum declaration:

enum Title {Prof, Dr, Mr, Mdm, Mrs, Miss, NA};

I'm trying to map the user input(0,1,2,3,4,5,AnyNumber) with correct value from enum like this:

std::map<std::string,Title> m;
m["0"] = Prof;
m["1"] = Dr;
m["2"] = Mr;
m["3"] = Mdm;
m["4"] = Mrs;
m["5"] = Miss;

std::string stitle;

cout << "\n" << "Title (0:Prof 1:Dr 2:Mr 3:Mdm 4:Mrs 5:Miss Any:NA): ";
cin >> stitle;
Title title = m[stitle];
cout << title; // output 1 when I input 1, output 2 when I input 2 and so on 

I expect the above code should be working but whatever I input will be the output from cout but not the value from enum list. What's the problem with my code?

标签: c++ input enums
1条回答
该账号已被封号
2楼-- · 2019-03-07 18:24

An enum does not really store a series of characters as you seem to think, it just provides new names for some values of the underlying type (in your case, int). (This is somewhat simplified of course, but good enough to explain the observed behavior.)

Thus, printing an enum-element does not print its "name", but will result in the element being converted to the underlying type and then printed.

查看更多
登录 后发表回答