C++ Primer Plus Chapter 6 Exercise 7

c plus plusThere are a number of ways to do exercise 7. My approach uses the switch statement suggestion to keep tabs of vowels. Also, it analyses one word at a time except you have to press enter after each word for it to tally it appropriately. As mentioned, this could be completed multiple ways. Take a look at my solution below:

7.Write a program that reads input a word at a time until a lone q is entered. The program
should then report the number of words that began with vowels, the number that began
with consonants, and the number that fit neither of those categories. One approach is to
use isalpha() to discriminate between words beginning with letters and those that
don’t and then use an if or switch statement to further identify those passing the
isalpha() test that begin with vowels. A sample run might look like this:
Enter words (q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words beginning with vowels
4 words beginning with consonants
2 others

#include <iostream>
#include <string>

using namespace std;

const int size = 50;

int main()
char word[size];
int vowels = 0;
int consonants = 0;
int others = 0;

cout << "Enter words (q to quit): ";

while(cin.get(word, size) && (word[0] != 'q' || word[0] != 'Q'))
char * ch = new char;
*ch = word[0];

case 'a' : vowels++;
case 'e' : vowels++;
case 'i' : vowels++;
case 'o' : vowels++;
case 'u' : vowels++;
default  : consonants++;
cin.get(); // keep grabbing words after enter is pressed
delete ch;
cout << vowels << " words beginning with vowels\n"
<< consonants << " words begining with consonants\n"
<< others << " others";

return 0;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s