1

我有一个简短的程序,旨在通过首先测试以查看数组中的字符是否为字母字符(跳过任何空格或标点符号)来计算字符串中辅音的数量。我的“if (isalpha(strChar))”行代码不断出现调试断言失败。

"strChar" 是一个在 for 循环中分配了 char 值的变量

抱歉,如果这是一个补救问题,但我不确定我哪里出错了。提前感谢您的帮助!

#include <iostream>
#include <cctype>
using namespace std;
int ConsCount(char *string, const int size);


int main()
{
    const int SIZE = 81; //Size of array
    char iString[SIZE]; //variable to store the user inputted string

    cout << "Please enter a string of no more than " << SIZE - 1 << " characters:" << endl;
    cin.getline(iString, SIZE);

    cout << "The total number of consonants is " << ConsCount(iString, SIZE) << endl;
}

int ConsCount(char *string, const int size)
{
    int count;
    int totalCons = 0;
    char strChar;

    for (count = 0; count < size; count++)
    {
        strChar = string[count];
        if (isalpha(strChar))
            if (toupper(strChar) != 'A' || toupper(strChar) != 'E' || toupper(strChar) != 'I' || toupper(strChar) != 'O' || toupper(strChar) != 'U')
            totalCons++;
    }
    return totalCons;
}
4

3 回答 3

1

我想问题是你总是循环遍历 81 个字符,即使输入的字符更少。这会导致一些随机数据馈送到isalpha().

无论如何,我会更改为要使用的代码,std::string而不是char iString[SIZE]获取输入文本的实际长度。

于 2018-03-27T12:53:13.077 回答
0

函数ConsCount(char* string, const int size)应该是这样的:

int ConsCount(char *string, const int size)
{
    int consCount = 0;

    char* begin = string;
    for (char* itr = begin; *itr != '\0'; ++itr)
    {
        if (isalpha(*itr)) {
            char ch = toupper(*itr);

            switch(ch) {
                case 'A':
                case 'E':
                case 'I':
                case 'O':
                case 'U':
                    break; // If ch is any of 'A', 'E', 'I', 'O', 'U'
                default:
                    ++consCount;
            }
        }
    }

    return consCount;
}

如您所见,我将 if 语句替换为 switch 以获得更好的可读性并char*用作迭代器来迭代字符串。您可以删除int size代码中未使用的参数。

我还建议您使用std::string安全代码。它还为您提供了一个iterator类来迭代std::string.

于 2018-03-27T13:01:22.717 回答
-1
int ConsCount(char *string, const int size)
{
    int consCount = 0;

    char* begin = string;
    for (char* itr = begin; *itr != '\0'; ++itr)
    {
        if (isalpha(*itr)) {
            char ch = toupper(*itr);

            switch(ch) {
                case 'A':
                case 'E':
                case 'I':
                case 'O':
                case 'U':
                    break; // If ch is any of 'A', 'E', 'I', 'O', 'U'
                default:
                    ++consCount;
           }
        }
    }

    return consCount;

尝试这个

}

于 2018-03-27T13:05:49.907 回答