比较要打印的字符数组

Compare character arrays to be printed

本文关键字:字符 数组 打印 比较      更新时间:2023-10-16
#include <iostream>
using std::cout;
using std::endl;
int main()
{
    int i, a = 0, j;
    int num[26]={};
    char alp[26], ch[100]={'s', 'd', 'd', 'e', 'f', 'g' };
    //Initialize array alp[] with alphabets a to z.
    for(int i=97; i <(97+26) ; i++)
        alp[i-97]=i;
    for (i = 0; i < 26; i++)
    {
        for (j = 0; ch[j] != ''; j++)
        {
            if (alp[i] == ch[j])
                num[i] = a++;
        }
        cout << endl << string(5, ' ') << alp[i] << string(5, ' ');
        if (num[i])
            cout << num[i] << endl;
        else cout << endl;
    }
    return 0;
}

没有编译错误。但是,当我打印时,我会得到垃圾值(num[i](。基本上,我将一个字符数组与一个字母数组进行比较,然后打印一个表,其中包含ch数组包含的字母数(alp数组,已经用所有字母a到z初始化(。

您的数组num未初始化,因此它会得到垃圾值。如果你想用0初始化它,请更改你的代码:

int num[26] = {};

为了解决这个问题,当您初始化循环中使用的每个值时,问题会变得更清楚,但效果较差

int i, a = 0, j;
int num[26];
for (i = 0; i < 26; i++)
{
    num[i]=0;
...

当然,初始化是更短、更干净的解决方案。