用大写和小写字母初始化数组

Initialize an array with both upper and lowercase letters C++

本文关键字:初始化 数组 小写字      更新时间:2023-10-16
//Loop to initialize the array of structs; set count to zero
for(int i = 0; i < 26; i++)
{
    //This segment sets the uppercase letters
    letterList[i].letter = static_cast<char>(65 + i);
    letterList[i].count = 0;
    //This segment sets the lowercase letters
    letterList[i + 26].letter = static_cast<char>(97 + i);
    letterList[i + 26].count = 0;
}

//这似乎不工作!

整个程序,取一个文本文件,读取它,然后打印出使用的每个字母,使用的次数和出现的百分比…但是,我的输出仍然是:

字母计数出现百分比

¿0 0.00%

52倍……

我没有看到这个代码输出有任何问题

    letterType letterList[52];
    for(int i = 0; i < 26; i++)
    {
        //This segment sets the uppercase letters
        letterList[i].letter = static_cast<char>('A' + i);
        letterList[i].count = 0;
        //This segment sets the lowercase letters
        letterList[i + 26].letter = static_cast<char>('a' + i);
        letterList[i + 26].count = 0;
    }
    for (int i = 0; i < 26 * 2; i++)
        cout<<letterList[i].letter<<" "<<letterList[i].count<<endl;
for(int i=0, c='a'; i<26; i++)
{
        letterList[i] = c++;
}
for(int i=26,c='a'; i<52; i++)
{
        letterList[i] = toupper(c++);
}
或者,你可以这样替换第二个for循环:
for(int i=26,c='A'; i<52; i++)
{
        letterList[i] = c++;
}

编辑

根据您对struct
的要求假设您的struct有一个char成员,并且每个struct实例携带每个字母,这是代码:

struct letterType
{
    char letter;
};
int main()
{
    struct letterType letterList[52];
    char c;
    for(int i=0, c='a'; i<26; i++)
    {
            letterList[i].letter = c++;
    }
    for(int i=26,c='a'; i<52; i++)
    {
            letterList[i].letter = toupper(c++);
    }
    for(int i=0; i<52; i++)
    {
            cout<< letterList[i].letter << endl;
    }
}