C 投票计划帮助(初学者)

C++ voting program help (beginner)!

本文关键字:初学者 帮助 计划      更新时间:2023-10-16

我在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;
}

因此,您会看到时循环。如果我只按ENTER,我希望程序停止。但是当我这样做时,什么都没有发生。为什么?给我一个线索!

更改输入函数,以便它通过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;
}