counting vowels

closed account (DG6DjE8b)
so question is to count the # of vowels and print it out. But my answer keeps saying '0'
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

int numVowel = 0;
char character = ' ';


cout << "Enter a sentence: ";
cin>>character;
if ((character == 'a')||(character == 'A')||(character == 'e')||
(character == 'E')||(character == 'i')||(character == 'I')||
(character == 'o')||(character == 'O')||(character == 'u')||
(character == 'U')||(character == 'y')||(character == 'Y'))
{
++numVowel;
}



cout <<"Total number of vowels:"<<numVowel<<endl;

return 0;
}
You are only accepting input of a single character, and counting only that single character. (Try a sentence that begins with a vowel, like "Ahoy there!")

You need to input a string (getline( cin, s );) and use a loop to iterate through the values in s.

Hope this helps.
closed account (DG6DjE8b)
I am sorry i am pretty new to C++. Could you please explain more?
To get a string from the user (more than one character), use something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
using namespace std;

int main()
{
  string s;  // Here is the string

  cout << "What is your name? ";
  getline( cin, s );  // Get it from the user

  cout << "Hello, " << s << "!\n";  // Use it
}

You can see each character in the string with a loop:

1
2
for (unsigned i = 0; i < s.size(); i++)
  cout << s[ i ] << "\n";

Check each s[ i ] to see if it is a vowel, just like you did with character above.


JSYK, it might be worth your time to look through the tutorials on this site. They are actually pretty concise and help you as you go.
http://www.cplusplus.com/doc/tutorial/

The trick to programming is to not give up.

Hope this helps.
You can also wrap your entire code in a while loop, which should solve the problem:

1
2
3
4
5
6
7
8
9
10
while (cin>>character)
{
    if ((character == 'a')||(character == 'A')||(character == 'e')||
        (character == 'E')||(character == 'i')||(character == 'I')||
        (character == 'o')||(character == 'O')||(character == 'u')||
        (character == 'U')||(character == 'y')||(character == 'Y'))
    {
        ++numVowel; 
    }
}
Topic archived. No new replies allowed.