如何映射用户输入与枚举值? [英] How to map user input with enum value?

查看:293
本文介绍了如何映射用户输入与枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的枚举声明:

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

我正在尝试映射用户输入(0,1,2,3,4,5 ,AnyNumber),正确值来自枚举如下:

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 

我期望上面的代码应该是正常的,但是无论我输入什么,都将是 cout 的输出,而不是枚举列表中的值。我的代码有什么问题?

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?

推荐答案

枚举存储一些您似乎认为的字符,它只为基础类型的一些值(在您的情况下, int )提供新名称。 (这当然有些简化,但足够好解释观察到的行为。)

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.

这篇关于如何映射用户输入与枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆