你如何计算菜单中辅音和元音的数量

时间:2014-01-27 20:33:47

标签: c++ string loops

我的节目有问题,元音和辅音的计算方法有问题

#include<iostream>
using namespace std;

int main(){
    int num[10],even = 0,odd = 0;
    char choice;
    int vowelcount = 0;
    int concount = 0;
    string word;

    cout<<"MENU:"<<endl<<"[N]umber"<<endl<<"[L]etter"<<endl<<"Choice : ";
    cin>>choice;

    switch(choice){
    case 'n': case 'N':
        cout << "Enter 10 integers: \n"; 
        for(int i = 0; i < 10; i++) { 
            cin >> num[i]; 
            if((num[i] % 2) == 0) { 
                even++; 
            } 
        } 
        odd = 10 - even; 
        cout << "Even: " << even << endl; 
        cout << "Odd: " << odd << endl; 
        system("pause");
        cout<<"Do you want to repeat the program ? Y/N ";
        break;

    case 'l': case 'L':
        cout<< "Enter 10 Letters : \n";
        cin>> word;
        for (int i=0; word [i] != '\0'; i++){
            word[i] = tolower (word[i]);
            for (int i=0; word [i] != '\0'; i++)
                switch(choice){
                case 'A' :
                case 'E' :
                case 'I' :
                case 'O' :
                case 'U' :
                    vowelcount++;
                    break;
                default:
                    concount++;
                }
        }
        cout<<" total vowels = " <<vowelcount << endl;
        cout<<" total consonant = " <<concount << endl;
        system("pause");
        return 0;
    }
}

2 个答案:

答案 0 :(得分:1)

好的,这里有几个问题。首先,总是尝试提供更多信息,然后“出现问题”。我只是将你的例子复制到visual studio中,很快就能找出你的问题,但是有了更多的信息,我可能根本不需要这样做。此外,整个问题不需要大写。 :)

所以......你的switch语句正在一个名为choice的变量上完成。此变量是您用来选择菜单选项的变量。您需要在正在测试的角色上运行switch语句。此外,你有两个循环,你只需要一个。

现在,因为你正在选择运行程序并且你有两个循环,每次循环选择总是'l'或'L'是辅音,但它运行的次数相等于输入字符串的长度平方。因此,对于元音的数量,你的响应为0,因为它从未看到任何元音,并且输入字符串的长度是平方的,因为你有嵌套的循环并且它多次计数“L”。

答案 1 :(得分:0)

您可以使用switchstring方法,而不是使用std::string::find语句:

std::string vowels = "AEIOUaeiou";
std::string consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz";

if (vowels.find(letter) != std::string::npos)
{
  ++vowelcount;
}
else
{
    if (consonants.find(letter) != std::string::npos)
    {
        ++consonantcount;
    }
}
相关问题