我正在编写一个 C++ 控制台应用程序,我正在将 a
转换为 1
,将 b
转换为 2
等等。问题是,它正在输出 48 和 52 之类的数字 - 即使我基于它的数组最多只能达到 26。
代码如下:
void calculateOutput() {
while (input[checkedNum] != alphabet[checkedAlpha]) {
checkedAlpha++;
if (checkedAlpha > 27) {
checkedAlpha = 0;
}
}
if (input[checkedNum] == alphabet[checkedAlpha]) {
cout << numbers[checkedAlpha] << "-";
checkedAlpha = 0;
checkedNum++;
calculateOutput();
}
}
这是我的数字和字母数组:
char alphabet [27] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','o','p','q','r','s','t','u','v','w','x','y','z',' '};
int numbers [27] = { '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','0' };
最佳答案
它是int
数组,所以它意味着它将保存字符的ASCII值。
如果你仔细看ASCII table , 你会发现 48,49,50,... 是数字 0,1,2,... 的 ascii 值
您要做的是减去表中第一个数字的值 -> '0' (48)
cout << numbers[checkedAlpha] - '0' << "-";
或者更好,将数字保存为数字而不是字符
int numbers [27] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18',19,20,21,22,23,24,25,26,0 };
顺便说一句。这是让你更容易的提示
tolower(inputAlphabet[index]) - 'a' + 1 // For 'a' output is 1 and so on :-)
关于c++ - 数组输出不正确 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45809558/