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;
inFile.open("FastRodeTheKnight.txt");
char readChar;
string line;

while (! inFile.eof())
{
	while (getline(inFile, line))
	{
		inFile.get(readChar);
		if (readChar = ' ')
			countWhite++;
		else if (readChar = 'A' || readChar = 'a')
			countVowel++;
		else if (readChar = 'E' || readChar = 'e')
			countVowel++;
		else if (readChar = 'I' || readChar = 'i')
			countVowel++;
		else if (readChar = 'O' || readChar = 'o')
			countVowel++;
		else if (readChar = 'U' || readChar = 'u')
			countVowel++;
		else
			countCons++; 
	}
	countLine++;
	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! :)

Dave

This article has been dead for over six months. Start a new discussion instead.