C++ count vowel consonants from a text file

别说谁变了你拦得住时间么 提交于 2021-02-07 11:14:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!