Ok, you are welcome. The most important part is: do you understand why it works now and was not working before? And can you make some optimization to the code? For example you could have only one for-loop and check the characters while you read them, or you could read a word (not char by char) and then process it...
Anyway, for any other information, just drop me a line.
What if the user enters the code for ' 'or '.' or '$'? You are counting non-vowels, which is not the same thing as counting consonants.
You can do this efficiently with some C library functions:
- tolower() converts a uppercase letters to lower case, leaving other values unchanged.
- isalpha() returns true if the character is a letter
- Both of these take an integer argument that must be a character value or EOF.
#include <iostream>
#include <string>
#include <cctype>
usingnamespace std;
int
main()
{
string vowels("aeiou");
string dta;
unsigned total=0;
while (getline(cin, dta)) {
for (int i=0; i<dta.size(); ++i) {
int ch = (unsignedchar)dta[i];
if (isalpha(ch) &&
vowels.find(tolower(ch)) == string::npos) {
cout << dta[i];
++total;
}
}
cout << '\n';
}
cout << "total of " << total << " consonants\n";
return 0;
}
The trickiest part here is line 16. char can be signed so the values are -128 to 127. But you want values 0 to 255. Line 16 does this conversion by converting to unsigned char, which will then get widened to int. Note that int ch = (unsigned)dta[i] doesn't work because the char dta[i] will be widened first, which causes sign extension.