-
September 11th, 2009, 01:49 PM
#1
help with finding characters with find()
I'am trying to build a program where I have to find all the vowels in a string.
I have managed to make this work when I check for a string where I declare a variable for example:
string phrase = "aabb eebb";
my code works perfectly and it finds four vowels, however when I changed the code to change the variable due to user input for example:
string phrase;
cin >> phrase;
and I type in the exact same string it only finds 2 vowels.
I just don't really understand the difference between the space in the string " " and the space in the input as to why I am getting two different answers. If someone could help out that would be awesome.
thanks,
anyway here is my code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int numVowels(string const, char const);
int main (int argc, char * const argv[])
{
string phrase;
cout << "Type in a phrase to search for vowels" << endl;
cin >> phrase;
int n_vowels = numVowels(phrase, 'a');
n_vowels += numVowels(phrase, 'e');
n_vowels += numVowels(phrase, 'i');
n_vowels += numVowels(phrase, 'o');
n_vowels += numVowels(phrase, 'u');
cout << "There were " << n_vowels << " vowels in your phrase." << endl;
return 0;
}
int numVowels(string phrase, char ch)
{
int vowels = 0;
size_t chFinder = phrase.find(ch, 0);
while (chFinder != string::npos)
{
vowels++;
size_t chSearch = chFinder + 1;
chFinder = phrase.find(ch, (chSearch));
}
return vowels;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|