How about this?
#include <cctype>
#include <cstring>
#include <iostream>
#include <string>
int main(int argc,char **argv) {
bool useStrInput = true; //change this to false to use C-string
int counts[26];
int characters = 0,
consonants = 0,
vowels = 0;
for(int i = 0; i < 26; i++) {
counts[i] = 0;
}
std::cout << "Enter a string:" << std::endl;
if(useStrInput) {
std::string str_input;
std::getline(std::cin,str_input);
std::cout << "You entered: " << str_input << std::endl;
for(unsigned int j = 0; j < str_input.length(); j++) {
int c = std::toupper(str_input[j]) - 'A';
if(c >= 0 && c <= 25) {
++counts[c];
}
}
}
else {
char cstr_input[256];
std::cin.getline(cstr_input,256);
std::cout << "You entered: " << cstr_input << std::endl;
for(unsigned int j = 0; j < std::strlen(cstr_input); j++) {
int c = std::toupper(cstr_input[j]) - 'A';
if(c >= 0 && c <= 25) {
++counts[c];
}
}
}
consonants = counts['B' - 'A'] + counts['C' - 'A'] + counts['D' - 'A']
+ counts['F' - 'A'] + counts['G' - 'A'] + counts['H' - 'A']
+ counts['J' - 'A'] + counts['K' - 'A'] + counts['L' - 'A']
+ counts['M' - 'A'] + counts['N' - 'A'] + counts['P' - 'A']
+ counts['Q' - 'A'] + counts['R' - 'A'] + counts['S' - 'A']
+ counts['T' - 'A'] + counts['V' - 'A'] + counts['W' - 'A']
+ counts['X' - 'A'] + counts['Y' - 'A'] + counts['Z' - 'A'];
vowels = counts['A' - 'A'] + counts['E' - 'A'] + counts['I' - 'A'] + counts['O' - 'A'] + counts['U' - 'A'];
characters = consonants + vowels;
std::cout << "This has " << characters << " characters, "
<< vowels << " vowels, and "
<< consonants << " consonants." << std::endl;
return(0);
}
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59:





by: jhshuklaPosted on 2009-08-10 at 20:32:32ID: 25065997
If your code is working for c-style strings, then changing to stl strings is easy.
std::getline(cin, user_input);
for(int c=0;c !=user_input.length();++c)
this is optional:
you don't need to create 256-count array. you can achieve the same results with size 26 using