I need some help with my homework assignment fir my C++ class, here is a description of the assignment:

Write a program that reads this file and finds the longest word that contains only a single vowel (a,e,i,o,u). Output this word (there will actually be several ties for the longest word. Your program only needs to output one of these words).

I managed to write a program that will find the longest word, I am having issues finding a single vowel.

At first I thought I might need to use a "for statement" to do this, but I could not figure out a way to make it work.

Here is the code that I have so far:

#include <iostream>
#include <fstream>
#include <cstdlib>

std::string word; 
std::string longest_word; 
using namespace std;

int main()
 ifstream inStream;
 string  word;
 string longest_word;
int size;

inStream.open("words.txt", ifstream ::in);

while(inStream) {
       inStream >> word;

    if (word.size () > longest_word.size ())
    longest_word = word;


cout << longest_word << endl;
 inStream.close( );   
    return EXIT_SUCCESS;

Would it even be possible to use a "for loop" for this program?

6 Years
Discussion Span
Last Post by XinJiki


bool is_single_vowel(string word)
     //All words contain at least 1 vowel; find it:
     size_t found = word.find_first_of("aeiouAEIOU");

     //Handle Special Case:  If no vowel was detected, word must be using single 'y' as a vowel:
     if(found == string::npos)

          return true;

     //Attempt to find any occurance of a second vowel
     found = word.find_first_of("aeiouAEIOU", found+1);

     //If no second vowel was detected, return TRUE
     if(found == string::npos)

          return true;

     //Else word contains two or more vowels

          return false;

Try upgrading your test condition in Line #28 to this:

if (word.size () > longest_word.size () && is_single_vowel(word))

Edited by Clinton Portis: n/a

This question has already been answered. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.