c++ - 数组输出不正确 - C++

标签 c++

我正在编写一个 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/

相关文章:

c++ - Visual Studio 2013 迁移 : Cannot open include file: 'dxerr8.h' : No such file or directory

c++ - 交叉编译库链接 (linux) (C++/C)

c++ - 带有原始输入的精密触摸板的 X 和 Y 坐标

c++ - 内部和外部编码与 Unicode

c++ - 条件传递链接库

C++ 预期的类型说明符

c++ - Matlab中调用C++函数,处理二维数组,指针的指针?

c# - 添加或修改 True Type 字体 (TTF) 中字形的简单方法

c++ - 声明嵌套结构实例的语法

c++ - MPI 发送矩阵列 (C++)