gpt4 book ai didi

c++ - 如何将 char 值转换为特定的 int 值

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:21 26 4
gpt4 key购买 nike

我有一个作业,我必须编写一个程序,允许一个人输入一个七个字母的单词并将其转换为电话号码(例如 1-800-PAINTER 到 1-800-724-6837)。我正在尝试将每个字母转换为特定数字以输出给用户,每个字母对应于电话键盘上的数字(因此 a、A、b、B 或 c、C 等于 1,即更多信息:https://en.wikipedia.org/wiki/Telephone_keypad)。

目前我已将其设置为输入单词的每个字母分别代表一个 char 变量 1、2、3、4、5、6 或 7。然后,使用 switch 和 if 语句,想法是将 char 转换为 xtwo = 2、xthree = 3 等的 int 变量。但这不起作用。有更好的方法吗?

代码示例(直到第一次切换,尽管它主要是像这样的重复模式):

int main()
{
char one, two, three, four, five, six, seven;

cout << "Enter seven letter word (1-800-***-****): " << "\n";

cin >> one >> two >> three >> four >> five >> six >> seven;
int xtwo = 2; int xthree = 3; int xfour = 4; int xfive = 5; int xsix = 6; int xseven = 7; int xeight = 8;
int xnine = 9;

switch (one)
{
case 1:
if (one == 'a' || one == 'b' || one == 'c' || one == 'A' || one == 'B' || one == 'C')
{
one = xtwo;
}
break;
case 2:
if (one == 'd' || one == 'e' || one == 'f' || one == 'D' || one == 'E' || one == 'F')
{
one = xthree;
}
break;
case 3:
if (one == 'g' || one == 'h' || one == 'l' || one == 'G' || one == 'H' || one == 'L')
{
one = xfour;
}
break;
case 4:
if (one == 'j' || one == 'k' || one == 'l' || one == 'J' || one == 'K' || one == 'L')
{
one = xfive;
}
break;
case 5:
if (one == 'm' || one == 'n' || one == 'o' || one == 'M' || one == 'N' || one == 'O')
{
one = xsix;
}
break;
case 6:
if (one == 'p' || one == 'q' || one == 'r' || one == 's' || one == 'P' || one == 'Q' || one == 'R' || one == 'S')
{
one = xseven;
}
break;
case 7:
if (one == 't' || one == 'u' || one == 'v' || one == 'T' || one == 'U' || one == 'V')
{
one = xeight;
}
break;
case 8:
if (one == 'w' || one == 'x' || one == 'y' || one == 'z' || one == 'W' || one == 'X' || one == 'Y' || one == 'Z')
{
one = xnine;
}
break;
}

那么,本质上,一个字母的char变量如何转换为具体的int变量呢?

最佳答案

你可以使用 std::map .

例如,你可以

std::map<char,int> char_to_dig {
{'a',1}, {'b',1}, {'c',1},
{'d',2}, {'e',2}, {'f',2}
};

然后

char_to_dig['a']

会给你1


或者,您可以编写一个执行映射的函数。类似这样的事情:

int char_to_dig(char c) {
static const char _c[] = "abcdefghi";
static const int _i[] = { 1,1,1,2,2,2,3,3,3 };
for (unsigned i=0; i<9; ++i) {
if (_c[i]==c) return _i[i];
}
return -1; // some value to signal error
}

或者,不使用数组,您可以对 char 执行算术运算(因为它们只是小整数)。

int char_to_dig(char c) {
c = std::toupper(c);
if (c < 'A' || c > 'Z') return -1;
if (c == 'Z') return 9;
if (c > 'R') --c;
return ((c-'A')/3)+2;
}

这将为您提供类似本垫上的数字:

enter image description here


显然,有一个类似的 code golf question .

关于c++ - 如何将 char 值转换为特定的 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49505264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com