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:
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