I have an assignment for a class that wants me to read lines from a file and output a count of the vowels and whitespaces per line, and also count a total of characters in the entire document so I can calculate a % of vowels used overall. I did confirm that the file is being read by outputting the entire contents on the screen. My problem is reading each character, analyzing whether it is a whitespace, vowel, or neither, and getting the reading to stop at the end of a line and tally up the results before continuing to the next line. I've been looking at forums for help with this and haven't had any luck. Thanks for any help you can give!

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
int countLine = 0;
int countWhite = 0;
int countVowel = 0;
int countCons = 0;
ifstream inFile;
char readChar;
string line;

while (! inFile.eof())
	while (getline(inFile, line))
		if (readChar = ' ')
		else if (readChar = 'A' || readChar = 'a')
		else if (readChar = 'E' || readChar = 'e')
		else if (readChar = 'I' || readChar = 'i')
		else if (readChar = 'O' || readChar = 'o')
		else if (readChar = 'U' || readChar = 'u')
	cout<<"Line "<<countLine<<": "<<countVowel<<" vowels, "<<countWhite<<" white spaces"<<endl;

return 0;

You should use getline() to get a line at a time as a string. Then you can use the [] operator to get each character and analyse it.

Alternatively, you could use the std::count function: http://programmingexamples.net/index.php?title=CPP/Strings/CountCharacters

on each vowel. You may want to convert the whole string to lowercase (there is a function for this: http://programmingexamples.net/index.php?title=CPP/Strings/Case_Conversion) so you only have to search each vowel once.

See how these examples work everyone! :)


Be a part of the DaniWeb community

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