Revert Revert - 1 month ago 10
C++ Question

Counting vowels and consonants

My program keeps crashing every time I enter an input even though I use a system pause method and displays the same number of vowels and consonants that is incorrect. What's going on?

int main() {
// declare vars
char ch;
int vowels = 0;
int consonants = 0;
string word = "temp";

// prompt user
cout << "Please enter a word: ";
cin >> ch;

// loop vowels and consonants
for (int i = 0; i < word.size(); i++) {
ch = toupper(word[i]);
switch (ch) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
break;
default:
consonants++;
}
}

// show num of vowels and consanants
cout << "Number of Vowels: " << vowels << endl;
cout << "Number of Consanants: " << consonants << endl;

// pause and exit
getchar();
getchar();
return 0;
}

Answer

Some chages in your code :

#include <iostream>
#include <string>

using namespace std;

int main() {
    // declare vars
    char ch;
    int vowels = 0;
    int consonants = 0;
    string word = "temp";

    // prompt user
    cout << "Please enter a word: ";
    cin >> word;

    // loop vowels and consonants
    for (int i = 0; i < word.size(); i++) {
        ch = toupper(word[i]);
        switch (ch) {
        case 'A':
            vowels++;
            break;
        case 'E':
            vowels++;
            break;
        case 'I':
            vowels++;
            break;
        case 'O':
            vowels++;
            break;
        case 'U':
            vowels++;
            break;
        default:
            consonants++;
        }
    }

    // show num of vowels and consanants
    cout << "Number of Vowels: " << vowels << endl;
    cout << "Number of Consanants: " << consonants << endl;

    // pause and exit
    getchar();
    getchar();
    return 0;
}