Jun 7, 2012 at 2:30am UTC
Hello I'm new to this forum and C++. I'm trying to write a program that reads input from a user and in a loop prints out only the vowels of that word. If possible may I know in simplest terms? Thanks.
#include <iostream>
using namespace std;
int main()
{
char array[30];
char vowel[6] = { 'a', 'e', 'i', 'o', 'u',};
for( int i = 0; i < 30; ++i )
{
array[ i ] = '\0';
}
cin.get(array , 30);
for ( int i = 0; i < 30; i++)
{
for ( int j = 0; j < 6; j++)
{
if (vowel[i])
{
cout << vowel[i] << " ";
}
}
}
system("Pause");
return 0;
}
I tried array[i] == vowel[j] in a for loop but, it says i and j are not initialized.
Jun 7, 2012 at 3:11am UTC
Why are you trying to use arrays if you're receiving strings from the user?
In modern C++, this program could look more like
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
#include <set>
const std::set<char > vowels = {'a' , 'e' , 'i' , 'o' , 'u' };
int main()
{
std::string line;
getline(std::cin, line);
for (char c: line)
if (vowels.count(c))
std::cout << c << " " ;
std::cout << '\n' ;
}
With an older compiler, you could use something like
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <string>
const std::string vowels = "aeiou" ;
int main()
{
std::string line;
getline(std::cin, line);
for (size_t i = 0; i < line.size(); ++i)
if (vowels.find(line[i]) != std::string::npos)
std::cout << line[i] << " " ;
std::cout << '\n' ;
}
online demo:
http://ideone.com/zzb7h
Although it would be better style if you wrote a function
isvowel()
that takes a char and returns a bool.
Last edited on Jun 7, 2012 at 3:12am UTC
Jun 7, 2012 at 2:28pm UTC
erm it's because I have not learned of functions yet. and the excercise I recieved says to make a program out of loops and arrays. Like being limited to see if I fully understand all that has been discussed so far. Thanks though.
Jun 7, 2012 at 3:19pm UTC
Thanks alot! this really helped and solved my problem.