gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:07 25 4
gpt4 key购买 nike

我是 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 循环。如果我只按回车键,我希望程序停止。但是当我这样做时什么也没有发生。为什么?给我一个线索!

最佳答案

更改您的输入函数,使其通过 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;
}

关于C++投票程序求助(初学者)!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22257416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com