所以我正在尝试计算元音、辅音和特殊字符的数量。我可以使用元音和特殊部分,但不能使用辅音。这是代码;
#include <iostream>
using namespace std;
void characterType(string);
int main()
{
string input = "Testing a sentence.";
characterType(input);
}
void characterType(string input)
{
int vowel, consonant, special = 0;
for (int i = 0; i < input.length(); i++)
{
char character = input[i];
if((character >= 'a' && character <= 'z') ||(character >= 'A' && character <= 'Z'))
{
character = tolower(character);
if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u')
{
vowel++;
}
else
{
consonant++;
}
}
else
{
special++;
}
}
cout<< "Vowels: " << vowel << endl;
cout<< "Consonant: " << consonant << endl;
cout<< "Special Character: " << special << endl;
}
我似乎无法弄清楚,有人知道吗?
最佳答案
定义
int vowel, consonant, special = 0;
仅将special
初始化为0
。另外两个变量未初始化,并且将具有不确定值。
您需要显式初始化所有想要具有特定初始值的变量:
int vowel = 0, consonant = 0, special = 0;
这就是为什么许多人建议每个语句只定义一个变量:
int vowel = 0;
int consonant = 0;
int special = 0;
关于c++ - C++ 计算字符串中辅音的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67800595/