Hi, I wrote this code for C++ Primer Plus, but I don't really get why it doesn't work.
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char ch;
string str;
int vowels = 0;
int consonants = 0;
int others = 0;
cout << "Enter words (q to quit):" << endl;
do
{
cin >> str;
ch = str[0];
if(isalpha(ch))
{
switch(ch)
{
case 'a':vowels++;
break;
case 'e':vowels++;
break;
case 'i':vowels++;
break;
case 'o':vowels++;
break;
case 'u':vowels++;
break;
default:consonants++;
break;
}
}
else
others++;
} while(ch != 'q');
cout << vowels << " words beginning with vowels" << endl;
cout << consonants << " words beginning with consontants" << endl;
cout << others << " others" << endl;
return 0;
}
When I change the ch to str in the while condition, it works pretty well. I found an alternative solution to the problem, but I am not really worried about the solution, but rather why my solution does not work. Nothing seems wrong with it and it compiles fine, but it doesn't seem to correctly count the number of vowels/consonants in the string.