问题
So one of the prompt of my lab is: "Find the percentage of vowels and percentage consonants in the English language. You should get a percentage of vowels = 37.4% and consonants = 62.5%."
Here is just my percentage function. I think there may be something wrong with the for loops but I can't seem to figure it out.. Thanks for the help!
int pv(string w) {
double numC=0;
double numV=0;
string fName;
ifstream inFile;
double pc;
cout << "Enter file name of dictionary (Mac users type in full path): ";
cin >> fName;
if (inFile.fail()) {
cout << "Error opening file" << endl;
exit(1);
}
while (!inFile.eof()) {
getline(inFile, w);
for (int i=0; i<w.length(); i++) {
if(w[i]==('a')||w[i]==('e')||w[i]==('i')||w[i]==('o')||w[i]==('u'))
numV=numV+1;
else {
numC=numC+1;
}
}
}
cout << numV;
return 0;
}
回答1:
Here is one of the solutions to your problem. Keep vowels, consonants and all characters in separate sets, read one character at the time from a file. If match is found in any of the sets then increment the appropriate counter. Calculate the percentage based on those counters:
#include <iostream>
#include <fstream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
set<char> vowels = { 'a', 'e', 'i', 'o', 'u' };
set<char> consonants = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'z', 'w', 'y' };
set<char> allchars = { 'a', 'e', 'i', 'o', 'u', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'z', 'w', 'y' };
char ch;
int vowelsCount = 0;
int consonantsCount = 0;
int percentageVowels = 0;
int percentageConsonants = 0;
int charactersCount = 0;
fstream fin("MyFile.txt", fstream::in);
while (fin >> ch) {
ch = tolower(ch);
if (find(allchars.begin(), allchars.end(), ch) != allchars.end())
{
charactersCount++;
}
if (find(vowels.begin(), vowels.end(), ch) != vowels.end())
{
vowelsCount++;
}
if (find(consonants.begin(), consonants.end(), ch) != consonants.end())
{
consonantsCount++;
}
}
percentageVowels = double(vowelsCount) / charactersCount * 100;
percentageConsonants = double(consonantsCount) / charactersCount * 100;
cout << "Vowels %: " << percentageVowels << endl;
cout << "Consonants %: " << percentageConsonants << endl;
getchar();
return 0;
}
来源:https://stackoverflow.com/questions/38490960/c-count-vowel-consonants-from-a-text-file