好的,我有这个任务,我必须提示用户提供有关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;
}
答案 0 :(得分:5)
读完一个数字(例如int
)之后,输入缓冲区中仍然有一个你还没有读过的新行。当您读取另一个数字时,会跳过任何空白区域(包括新行以查找数字。但是,当您读取字符串时,输入缓冲区中的换行符将被读取为空字符串。
要使其正常工作,您需要在尝试读取字符串之前从输入缓冲区中获取换行符。