I have a short program designed to count the number of consonants in a string by first testing to see if the character in the array is an alpha character (to skip any white space or punctuation). I keep getting a Debug Assertion Failed for my "if (isalpha(strChar))" line of code.
"strChar" is a variable that is assigned the char value in a for loop
Sorry if this is a remedial issue, but I'm not sure where I'm going wrong. Thanks in advance for any help!
#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;
}
The function ConsCount(char* string, const int size)
should be like this:
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;
}
As you can see I replaced the if statement with switch for better readability and using char*
as a iterator to iterate the string. You can remove the unused parameter int size
in your code.
And also I suggest you to use std::string
for the safe-code. It also provides you a iterator
class to iterate over the std::string
.