I'm trying to create a program that looks through a sentence and counts out the number of individual vowels and the total number of vowels. However, it outputs that each sentence has zero vowels. The code is below:
#include <iostream>
#include <cstring>
usingnamespace std;
int main()
{
string sentence;
int length = sentence.length();
int k, a = 0, e = 0, i = 0, o = 0, u =0;
cout << "Please enter a sentence to search: ";
getline (cin, sentence);
cout << endl;
for (k = 0; k < sentence.length(); k++);
if (a == 'a')
a++;
elseif (e == 'e')
e++;
elseif (i == 'i')
i++;
elseif (o == 'o')
o++;
elseif (u == 'u')
u++;
cout << "There are " << a << " a\'s, " << e << "e\'s " << i << " i\'s, " << o << " o\'s, and " << u << " u\'s." << endl;
return 0;
}
The output is:
Please enter a sentence to search:This is a sentence.
The sentence has 0 characters.
There are 0 a's, 0 e's, 0 i's, 0 o's, and 0 u's.
for (k = 0; k < sentence.length(); k++); // this semicolon is killing your loop
// the loop stops when it hits the semicolon
// so all this does is count k up from 0 to sentence.length()
// it doesn't do anything else
Your loop should be structured like this:
1 2 3 4
for(k = 0; k < sentence.length(); k++) // <- no semicolon
{ // <- braces
// put whatever you want to loop in here
}
You also are not checking any characters in the string. Take a look at this:
1 2
if (a == 'a')
a++;
a is your variable that counts the number of a's you found. You initialize it with 0. Therefore a == 0.
Is 0 == 'a'? No? That's why it's not incrementing.
You want to do this:
1 2
if( __a_character_from_the_string__ == 'a' )
a++;
So you have to ask yourself how to get a single character from the string.