c++ - 如何修复“条件中的变量声明必须具有初始化程序”
问题描述
我正在编写一个程序来计算用户输入的元音数量,但它给了我错误“条件中的变量声明必须有一个初始化程序”。你如何解决它?
#include <iostream>
using namespace std;
int isVowel(char c)
{
char Vowels[] = {'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'};
if (c in Vowels)
return true;
}
int main()
{
int n;
int numVowel = 0;
char c;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> c;
if (isVowel(c))
numVowel++;
}
cout << "Number of vowels = " << numVowel << endl;
return 0;
}
解决方案
采用std::find
#include <algorithm>
#include <array>
bool isVowel(char c)
{
static constexpr std::array<char, 10> Vowels{ 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' };
return std::find(Vowels.begin(), Vowels.end(), c) != Vowels.end();
}
推荐阅读
- javascript - 为什么 document.getElementById 只返回多个项目数组中的一个项目?
- javascript - 如何调试我的 JavaScript 下拉列表?
- sql - 生成基于外键约束自动连接表的选择查询的 SQL 选择?
- azure - 应用服务证书错误:参数 keyVaultCsmId 的值无效
- go - 如何让 Go Flag 包接受形式为 --telemetry.addr 的标志名称
- sql-server - ArgumentNullException:值不能为空。(参数“来源”)
- unity3d - 变换位置未返回正确值
- javascript - Aframe 自定义组件更新功能未触发
- php - PHP根据2个键从数组中删除重复项和它们的总和
- excel - 每次工作表在 excel VBA 中受保护或不受保护时记录