简体   繁体   English

C ++投票程序帮助(初学者)!

[英]C++ voting program help (beginner)!

Im new at cpp and i try to train myself with a little voting program. 我是cpp的新手,我尝试通过一些投票程序来训练自己。 You give in the parties and then the votes of the party. 您先让党参加,然后再给党投票。

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string sInput = " ";
    string sName1 = " ";
    string sName2 = " ";
    int iParty1 = 0;
    int iParty2 = 0;

    cout << "Name of the first party: ";
    cin >> sName1;
    cout << "Name of the second party: ";
    cin >> sName2;

    while (sInput != "")
    {
        cout << "Your vote: ";
        cin >> sInput;
        cout << endl;
        if (sInput == sName1)
        {
            iParty1++;
        }
        else
        {
            if (sInput == sName2)
            {
                iParty2++;
            }
            else
            {
                cout << "Wrong Input" << endl;
            }
        }

    }
    cout << sName1 << ": " << iParty1 << endl;
    cout << sName2 << ": " << iParty2 << endl;
    getchar();
    return 0;
}

So you see the while loop. 因此,您会看到while循环。 I want the program stop if i only press enter. 如果只按Enter,我希望程序停止。 But when i do it nothing happens. 但是当我这样做时,什么也没发生。 Why? 为什么? Give me a clue! 给我点暗示!

Change your input function so that it reads in the entire line via std::cin rather than a tokenized string. 更改输入函数,以使其通过std::cin而不是标记字符串读取整行。 You'll need to consider this read method since there can be spaces in the instream. 您需要考虑此读取方法,因为插播广告中可能会有空格。 Also, your Wrong Input code fires when you just put a blank line. 同样,当您只输入空白行时,也会触发您的错误输入代码。

Here's a fixed version: 这是固定版本:

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string sInput = " ";
    string sName1 = " ";
    string sName2 = " ";
    int iParty1 = 0;
    int iParty2 = 0;

    cout << "Name of the first party: ";
    cin >> sName1;
    cout << "Name of the second party: ";
    cin >> sName2;
    cin.ignore();

    while (sInput != "")
    {
        cout << "Your vote: ";
        getline(cin, sInput);
        cout << endl;
        if (sInput == sName1)
        {
            iParty1++;
        }
        else
        {
            if (sInput == sName2)
            {
                iParty2++;
            }
            else
            {
                cout << "Wrong Input" << endl;
            }
        }

    }
    cout << sName1 << ": " << iParty1 << endl;
    cout << sName2 << ": " << iParty2 << endl;
    getchar();
    return;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM