首页 > 解决方案 > 如何修复“条件中的变量声明必须具有初始化程序”

问题描述

我正在编写一个程序来计算用户输入的元音数量,但它给了我错误“条件中的变量声明必须有一个初始化程序”。你如何解决它?

#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;
}

标签: c++c++11

解决方案


采用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();
}

推荐阅读