【发布时间】:2018-09-05 20:56:49
【问题描述】:
我有一个简短的程序,旨在通过首先测试数组中的字符是否是字母字符(跳过任何空格或标点符号)来计算字符串中辅音的数量。我的“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;
}
【问题讨论】:
-
你给程序提供什么输入?
-
请将问题 edit 1. 指明您提供的输入,以及 2. 包括错误消息中显示 which 调试断言失败的部分。
-
如果只输入 3 个字符会怎样?你为什么一直循环到81?看到这个问题了吗?为什么不使用
std::string,这些字符串大小问题会自动处理? -
你永远不应该信任你的用户。验证你得到的输入。
-
int isalpha( int ch );采用int,因此会发生扩大。如果char已签名且strChar为负,则将导致未定义行为。 “如果 ch 的值不能表示为 unsigned char 或不等于 EOF,则行为未定义。” en.cppreference.com/w/cpp/string/byte/isalpha