c ++循环中的空间破坏

时间:2017-02-13 09:08:55

标签: c++ while-loop

#include <iostream>

using namespace std;

int main()
{
    string input; //User input
    char a; //Individual characters
    int score(0); //Final score
    int numa(0); //Number of a
    int numg(0); //Number of g
    int numm(0); //Number of m
    int numf(0); //Number of f
    int numk(0); //Number of k
    int numj(0); //Number of j

    cout << "Enter Text: "; //Requesting and storing user input
    cin >> input;
    cout << endl;

    a = input[0];
    cout << a;
    if(a != '!' || a != '.')
    {
        int num(0);
        while(num<=input.length())
        {
            a = input[num];
            switch(a)
            {
                case 'a':
                case 'A':
                    score += 1;
                    numa++;
                    break;

                case 'g':
                case 'G':
                    score += 2;
                    numg++;
                    break;

                case 'm':
                case 'M':
                    score += 3;
                    numm++;
                    break;

                case 'f':
                case 'F':
                    score += 4;
                    numf++;
                    break;

                case 'k':
                case 'K':
                    score += 5;
                    numk++;
                    break;

                case 'j':
                case 'J':
                    score += 8;
                    numj++;
                    break;

                default:
                    break;
            }
            num++;
        }
    }
    cout << "Number of a's (worth 1 point each): " << numa << endl;
    cout << "Number of g's (worth 2 point each): " << numg << endl;
    cout << "Number of m's (worth 3 point each): " << numm << endl;
    cout << "Number of f's (worth 4 point each): " << numf << endl;
    cout << "Number of k's (worth 5 point each): " << numk << endl;
    cout << "Number of j's (worth 8 point each): " << numj << endl;
    cout << endl;
    cout << "Total score: " << score;
}

此程序接受用户输入并根据其中包含的内容给出分数。字母a给出1分,g给2分,m给3分,f给4分,k给5分,j给8分。然而,它只有在有#34;!&#34;或&#34;。&#34;。所以,虽然啊!和aaa。得到3分,aaa!aa和aaa.aa也应该只给3分,因为&#34;!&#34;和&#34;。&#34;被忽视了。如果字符串没有以&#34;!&#34;结束,它也不应该运行。或&#34;。&#34;,aaaa!和aaaa。两者都返回4分,而aaaa则什么都不返回。麻烦的是,如果在switch语句中没有定义空格或说字母t,程序就不会运行。最终目标是这个声明,&#34;她做了一个熟悉的尝试恰到好处。&#34;得分为28分。

1 个答案:

答案 0 :(得分:0)

尝试将交换机的默认操作移动到其他案例的底部,而不是使用“继续”作为操作,而不是使用中断

switch(a){
    case 'a':
    case 'A':
     .....
    default:
         break;
}

另外如果不需要,你也不必测试其他条件。您可以使用普通的else子句替换它