Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print of vowels in a string

I attempted to create a program that let’s the user input a string of text and then create a subprogram that will print out all the vowels in that string. The problem with my program is that it only prints out the text once again.

So my terminal will look like:

Enter text: Feye
Feye

Instead of what I intend it to do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter text: Feye
eye

This is my code and I wonder what’s wrong of it. Why doesn’t it print out the index like I ordered it to do in my if-statement?

#include <iostream>

using namespace std;

void print_vowels (string const & text)

{
    for (int i {}; i < text.size(); ++i)
    
    {
        if (text.at(i) == 'a' || 'e' || 'i' || 'o' || 'u' || 'y')
        
        {
            cout << text.at(i);
        }
    }
}

int main()
{
    string text {};
    
    cout << "Enter text: ";
    getline(cin,text);
    
    print_vowels(text);

    return 0;
}

I have also tried putting text[i] instead of text.at(i) but I get the same results unfortunately.

>Solution :

This might help:

#include <iostream>
#include <string>


void print_vowels( std::string const & text )
{
    for ( std::size_t idx {}; idx < text.size(); ++idx )
    {
        if ( text[idx] == 'a' || text[idx] == 'e' ||
             text[idx] == 'i' || text[idx] == 'o' ||
             text[idx] == 'u' || text[idx] == 'y' )
        {
            std::cout << text[idx];
        }
    }
}


int main( )
{
    std::string text { };
    
    std::cout << "Enter text: ";
    std::getline( std::cin, text );
    
    print_vowels( text );
}

Also, note that at member function has a performance hit since it also checks for out-of-range indices at run-time. So it’s better to use the [] operator in this case.

Sample input/output:

Enter text: Feye
eye
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading