How to map user input with enum value?

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!