Trying to write a program to count the number of vowels in a user specified file.

This is what I've come up with so far. My professor made it clear he wants us to use the string class to get familiar with it. I don't know what function to use to test the input file string for vowels. This example compiles and runs but prints out vowels = 4 which isn't correct. Any hints?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " <filename>" << endl;
    }
    else 
    {   
        ifstream file(argv[1]);
        if (!file.is_open())
        {
            cout << "Unable to open file." << endl;
        }
        else
        {
            string str;
            int vowels = 0;
            while (!file.eof())
            {
                //copy contents of file to string "str"
                getline(file, str);
                
                //check for occurences of vowels within "str" and increment "vowels" for
                //each occurence
                if ((str.find('a'||'A') || str.find('e'||'E') || str.find('i'||'I') ||
                     str.find('o'||'O') || str.find('u'||'U')) != string::npos)
                { 
                    vowels++; 
                }
            }
            file.close();
            cout << "There are " <<  vowels << " vowels in this file" << endl;
        }
    }
    return 0;
}
The problem is that str.find('a' || 'A') is basically just like saying str.find(true) -- it won't look for 'a' or 'A'; it'll just evaluate ('a' != 0) or ('A' != 0) and pass that result to find.

I would use find_first_of: (warning: code below untested)
1
2
3
4
5
6
auto vowelPos = str.find_first_of("aeiouAEIOU");
while (vowelPos != std::string::npos)
{
    ++vowels;
    vowelPos = str.find_first_of("aeiouAEIOU", vowelPos + 1); // Find next occurrence
}
Wow that worked! Thank you so much! I am fairly new to C++ so I am still getting used to the different functions. One thing though, in my code I used size_t instead of auto, what is auto?
In long double main's code snippet, vowelPos is technically
size_t.

auto is a C++11 declaration specifier keyword, which allows the compiler to deduce what type a variable should be based on its initialization expression.
In other words, std::string.find_first_of() returns a size_t object, therefore vowelPos will be a size_t.

You shouldn't worry about auto, seeing as how you're in a beginner class, and you're probably not using a C++11 compiler.
Topic archived. No new replies allowed.