Embek
Embek

Reputation: 27

C++ show vowel and consonant and count it

When user input number from 1 - 26 (which mean a to z), how to show the the letter and count how many vowel and consonant inside it.

Example: Users input=13 Then will show = a b c d e f g h i j k l m Vowel = 3 Consonant = 10

i just now how to count it not to show it

#include <iostream>
using namespace std;
int main (){
int vow=0, con=0;
char let;
.........
.........
if (let=='a' || let=='e' || let=='i' || let=='o' || let=='u'){vow++}
else{con++}
cout<<"Vowel = "<<vow<<endl;
cout<<"Consonant"<<con<<endl;
}

Upvotes: 0

Views: 2163

Answers (3)

jgroenen
jgroenen

Reputation: 1326

#include <iostream>
using namespace std;

/**
 * Checks if the given letter is a vowel.
 */
bool isVowel(char let) {
    return let == 'a' || let == 'e' || let == 'i' || let == 'o' || let == 'u';
}

/**
 * Returns the character for the given int.
 */
char toChar(int num) {
    return (char) ('a' + num - 1);
}

int main (void) {
    int vow = 0,
        con = 0,
        num,
        i;
    char let;
    cout << "Please enter a number: ";
    cin >> num;
    for (i = 1; i <= num; ++i) {
        let = toChar(i);
        if (isVowel(let)) vow++;
        else con++;
    }
    cout << "The letter was \"" << let
         << "\" and there were " << vow
         << " vowels and " << con
         << " consonants." << endl;
    return 0;
}

Upvotes: 1

slackmart
slackmart

Reputation: 4934

To show the letters, you can use a for loop, using a char as index.

int n = 13;
unsigned int vowel = 0;
unsigned int consonant = 0;
int a = (int)'a';
for (char letter = 'a'; (int)letter < a + n; letter++) {
    cout << letter << " ";
    if (is_vowel(letter)) vowel++;
    else consonant++;
}
cout << std::endl << "vowels: "<< vowel << " consonants: " << consonant << std::endl;

So, you must implement the is_vowel method.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117926

Your if statement does not do what you expect it to. The correct syntax for this is

if (let=='a' || let=='e' || let=='i' || let=='o' || let=='u')

The reason the current versions is incorrect is because it is equivalent to

if ((let=='a') or ('e') or ('i') or ('o') or ('u'))

So 'e', 'i', etc are being evaluated for truthiness and ord to the first condition. Only an empty string in this case will evaluate to false, all of these characters will be true. So your statement evaluates to

if ((let=='a') or true or true or true or true)

Which will always be true.

Upvotes: 1

Related Questions