用大写和小写字母初始化数组
Initialize an array with both upper and lowercase letters C++
//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;
}
}
相关文章:
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在函数内部的声明中初始化数组,并在外部使用它
- 为什么用结构初始化数组需要指定结构名称
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++使用另一个数组和新值初始化数组
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 在 constexpr 构造函数中初始化数组是否合法?
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 在构造函数中初始化数组
- 是否可以使用函数返回的值初始化数组
- 使用宏使用额外元素初始化数组
- 在循环中显示不同值的初始化数组
- 如何在macOS中的旧扩展clang和gcc编译器中初始化数组和向量
- 使用可变模板列表初始化数组,并放置new
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- 使用 c++ 中的函数初始化数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- C++ 使用变量而不是常量表达式初始化数组
- 在初始化列表中初始化数组的更好方法
- 在可变参数模板类中初始化数组