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?

Recommended Answers

All 2 Replies


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

Thank you very much. The program is running great!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.