I need to write a program that counts the number of vowels in a string. The string is written by the user. I know that the best way to do this is with Switch, however I couldn't figure out how to do it because switch would need to take a char as an argument and have the vowels as cases. I made the program work with many"if" statements as an alternative but I want to understand and make it work with switch.
/* A program that counts the number of vowels in a string */
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
string phrase;
int nbchar, i, vowel;
vowel = 0;
cout << "Write a phrase: " << endl;
getline(cin, phrase);
nbchar = phrase.size();
for (i = 0; i < nbchar; i++)
{
if (phrase[i] == 'a')
vowel++;
if (phrase[i] == 'i')
vowel++;
if (phrase[i] == 'e')
vowel++;
if (phrase[i] == 'u')
vowel++;
if (phrase[i] == 'o')
vowel++;
if (phrase[i] == 'y')
vowel++;
}
cout << "In this phrase there is " << vowel << " vowels" << endl;
return 0;
}
If someone could change my code with switch, it would be much appreciated as I spent many hours trying to figure out how to make it work but failed.
In my opinion it is better to write program without switch.
You should declare a string that will contain vowels. For example,
std::string vowels( "aeiouy" );
and then use your loop
1 2 3 4 5 6 7
int count = 0;
for ( i = 0; i < nbchar; i++ )
{
if ( vowels.find( phrase[i] ) != std:;string::npos ) count++;
}
cout << "In this phrase there is " << vowel << " vowels" << endl;
When you use the subscript operator [] in front of a string variable you get an expression which accesses a single character in the string (the expression will evaluate to a char). So while it would be illegal to use switch( phrase ), it's perfectly OK to use switch( phrase[i] )
Whatever approach you take, I think you should factor out your test into a little helper function so it behaves and looks like the stdlib isalpha(), isdigit(), isspace(), ... functions.
In particular, the condition and the code it triggers should never be on the same line, as that stuffs any chance of setting a meaningful breakpoint (debuggers like gdb and vc++ only understand filepath + line number).
Also note that this is one of the few cases where fall through (due to the lack of break statements) is safe to use.
/* A program that counts the number of vowels in a string */
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
string phrase;
int nbchar, i, vowel;
vowel = 0;
cout << "Write a phrase: " << endl;
getline(cin, phrase);
nbchar = phrase.size();
for (i = 0; i < nbchar; i++)
{
switch ( phrase[i] )
{
case'a':
case'e':
case'i':
case'o':
case'u':
case'y':
vowel++;
}
}
cout << "In this phrase there is " << vowel << " vowels" << endl;
return 0;
}