我不明白为什么我的代码返回了错误的值。输入“a”返回 97,“z”返回 122。我缺少什么?
int main()
{
enum Alphabet {a = 1, b = 2, c = 3,d = 4,e = 5,f = 6,g = 7,h = 8,i = 9,j = 10,k = 11,l = 12,m = 13,n = 14,o = 15,p = 16,q = 17,r = 18,s = 19,t = 20,u = 21,v = 22,w = 23,x = 24,y = 25,z = 26 };
int jon;
char input;
cout << "Enter a letter and I will tell you it's position in the alphabet ";
cin >> input;
while (!isalpha(input))
{
cout << "Try Again. Enter a letter and I will tell you it's position";
cin >> input;
}
Alphabet inputEnum = static_cast<Alphabet>(input);
cout<<inputEnum;
cin>>jon;
return 0;
}
最佳答案
枚举将编译时标识符(例如 a
、b
和 c
)与整数值相关联。它们不关联运行时 char
值(例如 'a'
、'b'
、'c'
,注意引号) 到整数。它们已经是整数,它们的值由您的实现所使用的字符集决定。几乎每个实现都使用 ASCII 或与 ASCII 兼容的东西,它解释了您获得的值。看来你想要的是一张 map :
std::map<char,int> alphabet;
alphabet['a'] = 1;
alphabet['b'] = 2;
etc...
或者也许是一个简单的函数:
int alphabet(char c)
{
switch(c)
{
case 'a': return 1;
case 'b': return 2;
etc...
}
}
如果您想假设字符集是 ASCII 或 ASCII 兼容(一个相当安全的假设),那么您的函数可以更简单:
int alphabet(char c)
{
if (c >= 'a' && c <= 'z')
return c - 'a' + 1;
else
// c is not a lowercase letter
// handle it somehow
}
关于c++ - 从 char 到枚举的 static_cast 分配了错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19416122/