print strings from the array

closed account (G60iz8AR)
How to print string from arrays with vowels ? Function is below

// Filter: only print those strings from the array that
// end with a vowel: 'a' 'e' 'i' 'o' or 'u'

#include <string> // string class
#include <iostream> // cin, cout: console I/O
#include <fstream> // ifstream, ofstream: file
#include <stdlib.h>
using namespace std;

const int CAP = 500;

bool endsWithVowel( string word ); // prototype here. Fully written function below main

int main()
{
ifstream infile;
string arr[ CAP ]; // CAPACITY is 500
int count=0; // how many strings stored in array so far

// TRY TO OPEN THE INPUT FILE "words.txt"
infile.open("words.txt", ios::in);
if ( infile.fail() )
{
cout << "Can't find words.txt. Are you sure it's in this directory?\n"
<< "Do a dir command to check.\n"
<< "Does it have a .txt.txt extension?\n";
exit(0);
}

while( count < CAP && infile >> arr[count] )
count++;
infile.close();

cout << count << " words stored into array from words.txt\n" ;
cout << "Now printing only those words from the array that end with a vowel:\n\n";

// DO *NOT* MODIFY THIS LOOP OR ANYTING ELSE IN MAIN.
// JUST FILL IN THE endsWithVowel FUNCTION BELOW MAIN

for ( int i=0 ; i< count ; i++ )
{
if ( endsWithVowel(arr[i]) )
cout << arr[i] << endl;
}

return 0;
}

// ================================================
// == == == Y O U F I L L I N F U N C T I O N B E L O W == == ==
// ================================================


// YOU FILL IN THIS METHOD TO RETURN TRUE IF AND ONLY IF
// THE WORD ENDS WITH A VOWEL: 'a', 'e', 'i, 'o' ,'u'

bool endsWithVowel( string word )
{
return false; // just to compile. You change as needed
}
I would do something like this:

1
2
3
4
5
6
7
8
9
bool endsWithVowel( string word )
{
if(word[word.size()-1] == 'a') return true;
else if(word[word.size()-1] == 'e') return true;
else if(word[word.size()-1] == 'i') return true;
else if(word[word.size()-1] == 'o') return true;
else if(word[word.size()-1] == 'u') return true;
else return false;
} 
1
2
3
4
5
6
7
8
9
10
11
12
13
bool doesEndWithVowel ( string word )
{
    char c = word[word.size() - 1];
    
    switch ( c ) {
        case 'a' :
        case 'e' :
        case ... :
            return true;
    }
    
    return false;
}
Topic archived. No new replies allowed.