gpt4 book ai didi

c++ - for 循环没有正确执行?

转载 作者:搜寻专家 更新时间:2023-10-31 00:43:48 25 4
gpt4 key购买 nike

好的,我有这个任务,我必须提示用户输入有关 5 个不同篮球运动员的数据。我的问题提示在 for 循环中,循环第一次对第一个玩家执行正常,但是当需要输入第二个玩家信息时,前两个问题提示一起在同一行上,我摆弄了这个,只是无法弄清楚,我确信我显然遗漏了一些小东西,感谢您提供有关如何解决此问题的任何建议。

这是输出:

Enter the name, number, and points scored for each of the 5 players.
Enter the name of player # 1: Michael Jordan
Enter the number of player # 1: 23
Enter points scored for player # 1: 64
Enter the name of player # 2: Enter the number of player # 2: <------- * questions 1 and 2 *

这是我的代码:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;


//struct of Basketball Player info
struct BasketballPlayerInfo
{
string name; //player name

int playerNum, //player number
pointsScored; //points scored

};

int main()
{
int index; //loop count
const int numPlayers = 5; //nuymber of players
BasketballPlayerInfo players[numPlayers]; //Array of players

//ask user for Basketball Player Info
cout << "Enter the name, number, and points scored for each of the 5 players.\n";

for (index = 0; index < numPlayers; index++)
{
//collect player name
cout << "Enter the name of player # " << (index + 1);
cout << ": ";
getline(cin, players[index].name);

//collect players number
cout << "Enter the number of player # " << (index + 1);
cout << ": ";
cin >> players[index].playerNum;

//collect points scored
cout << "Enter points scored for player # " << (index + 1);
cout << ": ";
cin >> players[index].pointsScored;
}

system("pause");
return 0;

}

最佳答案

在您读取一个数字(例如,int)之后,输入缓冲区中仍然有一个您尚未读取的换行符。当您读取另一个数字时,它会跳过任何空白(包括换行符以查找数字)。但是,当您读取一个字符串时,输入缓冲区中的换行符将被读取为空字符串。

要使其正常工作,您需要在尝试读取字符串之前从输入缓冲区中取出换行符。

关于c++ - for 循环没有正确执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10056065/

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