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

时间:2014-03-07 18:01:45

标签: c++ voting-system

我是cpp的新人,我尝试用一​​点投票计划训练自己。 你在党内交出,然后是党的选票。

#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;
}

所以你看到了while循环。如果我只按回车键,我希望程序停止。 但是当我这样做时没有任何反应。为什么?给我一个线索!

1 个答案:

答案 0 :(得分:0)

更改输入函数,使其通过std::cin而不是标记化字符串读入整行。您需要考虑这种读取方法,因为在内部流中可能存在空格。此外,当您输入空行时,您的错误输入代码会触发。

这是一个固定版本:

#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;
}