Help with initialization

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstring>

using namespace 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++;

else if (e == 'e')
e++;

else if (i == 'i')
i++;

else if (o == 'o')
o++;

else if (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.


I don't understand what I am doing wrong! :(
Last edited on
Line 16 is a loop that doesn't do anything.

1
2
3
4
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.

You have the same problem with e, i, o, and u.
Thanks for the quick reply, I really appreciate it.
Topic archived. No new replies allowed.