c++ - C++ 计算字符串中辅音的逻辑错误

标签 c++

所以我正在尝试计算元音、辅音和特殊字符的数量。我可以使用元音和特殊部分,但不能使用辅音。这是代码;

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

这是输出; enter image description here

我似乎无法弄清楚,有人知道吗?

最佳答案

定义

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/

相关文章:

c++ - 迷失在指针世界,通过数组写入变量

C++、OpenCV:异步运行 cuda::dft

c++ - 使用 MATLAB 'dos' 命令调用并行化可执行文件的行为不同于独立可执行文件

c++ - 使用 MinGW 和 sip 安装 pyqt5。 "make"命令在哪里?

C++ Linux 多线程套接字问题

c++ - 静态库链接程序 VS 源代码编译程序大小差异巨大

c++ - 使用 WinCrypt 进行 AES-128 加密

C++ 元编程 : Store integer by type

c++ - 指针和数组指向数组问题

c++ - 提取整数的数字元素