从char到enum的static_cast分配错误的值

时间:2013-10-17 00:14:11

标签: c++ enums static-cast

我无法弄清楚为什么我的代码返回了错误的值。 'a'的输入返回97和'z'returns 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;
}

3 个答案:

答案 0 :(得分:1)

枚举将编译时标识符(例如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
}

答案 1 :(得分:0)

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

获得你所追求的更简单的方法是:

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

答案 2 :(得分:0)

虽然这是一个老问题,但我想我可能会注意到这一点,以防其他人想要一种类似于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++;
        }
    }
}
相关问题