从字符到枚举分配错误值的static_cast
static_cast from char to enum assigning wrong value
我不知道为什么我的代码返回了错误的值。 输入"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 兼容的东西,这解释了你得到的值。 似乎你想要的是一张地图:
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++;
}
}
}
相关文章:
- 如何理解C++标准N3337中的expr.const.cast子句8
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- C++Cast运算符过载
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 收到错误"invalid use of non-static data member 'stu::n' "
- LNK1104:无法打开libpjproject-i386-Win32-vc14-Debug-Static.lib
- 我应该在 C++ 中何时/为什么使用 STATIC?
- 在VS2019项目中集成ImageMagick:x64-windows-static library
- 如何处理Boost Spirit X3导致Visual Studio 2019 "static initialization order fiasco"?
- "static char __ = []() -> char"的含义
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- 无法在 DLL 中链接 SDL2-static.lib
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- 错误:"cast"未命名类型void setCastDescription(std::string
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- C++线程"Call to non-static member function without an object argument"
- 出现这种错误的原因是什么"invalid use of non-static data member "
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- static是如何使用ClassA::m_variable处理所有类对象的
- 在[expr.static.cast]/4中,术语"一个可行函数"指的是什么