0
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main(int argc, char* argv[])
{
ifstream inf(argv[1]);
if (!inf)
 {
    cerr << "Error opening " << argv[1] <<  endl;
    return 1;
 }

char ch;
size_t count = 0;

string vowels = "aAeEiIoOuU";
size_t p;
p = vowels.find(ch);

inf >> ch;
while(!inf.eof())
{


    if (p != string::npos)
    {
        count++;
    }
 inf >> ch;      
}     


inf.close();
cout << "File " << argv[1] << " includes " << count << " vowels." << endl;
return 0;
}

I have problem with the part

 inf >> ch;
while(!inf.eof())
{
  if ( p != string::npos)
  {
    count++
  }
       inf >> ch;
}

Basically, the program look up the text.txt file and count how many vowels it have. I want to repeat inside of while loop. If I include "inf >> ch;" at the end of the while loop, the program counts the vowel wrong. If I do not, the program freezes when I run it. Can you please help me? Thank you.

hints :

I have to use

  1. string vowels = "aAeEiIoOuU";

  2. the function call vowels.find(ch) will return an index that is not string::npos if ch is a vowel.

  • 1
    Possible duplicate of [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Fantastic Mr Fox Jul 15 '16 at 16:57
  • @Ben I do not think so. It is a problem but they have a bigger problem with `p = vowels.find(ch);` – NathanOliver Jul 15 '16 at 16:59
  • Rather than use a manual loop at all, consider using [`std::count_if()`](http://en.cppreference.com/w/cpp/algorithm/count) instead, using [`std::istream_iterator`](http://en.cppreference.com/w/cpp/iterator/istream_iterator) for input, and a predicate function that checks for vowel characters. – Remy Lebeau Jul 15 '16 at 18:29
  • Thank you guys all. I solved it. –  Jul 15 '16 at 18:44

2 Answers2

2

Problem is that you call find outside of the loop, so possible fix is:

string vowels = "aAeEiIoOuU";
// p delcaration and call to find is removed from here
inf >> ch;
while(!inf.eof())
{
    size_t p = vowels.find(ch);
    if (p != string::npos)
    {
        count++;
    }
    inf >> ch;      
} 

but to avoid code duplicate this is better and cleaner:

while( inf >> ch )
{
    size_t p = vowels.find(ch);
    if (p != string::npos)
    {
        count++;
    }
} 
Slava
  • 40,641
  • 1
  • 38
  • 81
0

In this bit of code:

char ch;
...
p = vowels.find(ch);

You use ch without it being initialized. How can you know what the result of this program will be. Also read this.

Community
  • 1
  • 1
Fantastic Mr Fox
  • 27,453
  • 22
  • 81
  • 151