CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Hybrid View

  1. #1
    Join Date
    Sep 2009
    Posts
    4

    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;
    }

  2. #2
    Join Date
    Oct 2002
    Location
    Austria
    Posts
    1,284

    Re: help with finding characters with find()

    Code:
    cin >> phrase;
    The stream extractor >> stops reading when it finds a whitespace.
    Use getline() instead.
    Kurt

  3. #3
    Join Date
    Sep 2009
    Posts
    4

    Re: help with finding characters with find()

    Thanks Kurt.

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
  •  





Click Here to Expand Forum to Full Width

Featured