Picking out vowles from a cin operator

I am at this exercise relating to functions and the book says to create a function that outputs the number of vowels in a sequence of letters. I feel like I almost have it but when I compile any word that does not start with a vowel, I am told there are no vowels. The code only recognizes the first letter because it outputs "Vowel(s) when my input starts with a vowel. Can anyone lend a hand?

Also I have a burning question. To make things simpler, I was just going to put all the vowels in the alphabet into a variable named "vowels" but I found I can't put more than one assignment into one variable. This is what I tried: char vowel = "a" && "e" && "i".....etc. I googled around and found that an array would solve my problem but arrays are way beyond my knowledge. My question is how can I put more than one assignment into a single variable, if possible? Thanks.


#include <iostream>
#include <string>
using namespace std;

char isVowel (string word);

int main()
{
string word;

cout<<"Enter a word: ";
cin>> word;
cout<<endl;

cout<<isVowel(word);

return 0;
}

char isVowel (string word) //Start of function I am having problem with
{
int counter = 0;

if(word == "a" || word == "e" || word == "i" || word == "o" || word == "u")
{
counter++;
cout << "Vowel(s)";
}
else
cout << "No vowel(s)";
}

Please remember to use code tags when posting code (see right menu, <> button).

Now for your program.
You're using std::string, which is already a good thing.
The problem is: do you know what word == "a" does?
It checks if the user entered a as word.

So how do you count the vowels?
You go through all the elements of the string and check if they're vowels.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// passing string "by reference", it's faster
std::size_t countVowels(const std::string &s)
{
    const std::string vowels = "aeiouAEIOU";
    std::size_t count = 0;
    // you could use int instead of std::size_t if you wish, but not char

    // first tricky part: "iterate" the string
    // (this is the C++ way to examine all elements sequentially)
    for (std::string::const_iterator it = s.begin();
        it != s.end();
        ++it
        )
        // second tricky part, check if current character is also found
        // in the vowels string above
        if (vowels.find(*it) != std::string::npos) // if yes, increment count
            ++count;

    return count;
}


Also, if you add using namespace std; you may remove all the beginning std::'s.

http://cplusplus.com/reference/string/string/
http://cplusplus.com/reference/string/string/find/

Edit: tags, links
Last edited on
Topic archived. No new replies allowed.