从字符到枚举分配错误值的static_cast

static_cast from char to enum assigning wrong value

本文关键字:static cast 错误 字符 枚举 分配      更新时间:2023-10-16

我不知道为什么我的代码返回了错误的值。 输入"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;
}
枚举将

编译时标识符(如abc)与整数值相关联。 它们不会将运行时char值(如 'a''b''c'、注意引号)与整数相关联。 它们已经是整数,它们的值由您的实现使用的字符集确定。 几乎每个实现都使用 ASCII 或与 ASCII 兼容的东西,这解释了你得到的值。 似乎你想要的是一张地图:

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
}

好吧,字符(就像您的input变量一样)实际上只是一个整数值。当与字母相关联时,如 a ,它们按 ASCII 值进行。a的 ASCII 值为 97,b为 98,依此类推。

获得您所追求的目标的一种更简单的方法是:

int inputPosition = input - 'a' + 1;
cout << inputPosition;

虽然是一个老问题,但我想我可能会记下这一点,以防其他人想要一种方法来做类似于 OP 的事情。

遇到了同样的问题,但就像 OP 一样,我不想坐在那里,填写一个长长的 26 个案例开关块。因此,我想出了一个更好的,节省时间的方法:

#include <ctype.h>
#include <string>
// Takes in a alphabetic char, and returns 
// the place of the letter in the aplhabet as an int.
int AlphabetCode(char _char){
    // Used to compare against _char.
    char tempChar = 'A';
    // Cycle through the alphabet until we find a match.
    for (int cnt = 1; cnt < 26; cnt++) {
        if (tempChar == toupper(_char)) {
            return cnt;
        }
        else {
            // Increment tempChar.
            // eg: A becomes B, B becomes C etc.
            tempChar++;
        }
    }
}