繁体   English   中英

计算字符串 C++ 中的辅音时出现逻辑错误

[英]Logic error on counting consonants in a string 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;
}

这是output; 在此处输入图像描述

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

定义

int vowel, consonant, special = 0;

special0 其他两个变量未初始化并且具有不确定的值。

您需要显式初始化您希望具有特定初始值的所有变量:

int vowel = 0, consonant = 0, special = 0;

这就是为什么许多人建议每个语句只定义一个变量的原因:

int vowel = 0;
int consonant = 0;
int special = 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM