2

好的,我有这个任务,我必须提示用户输入关于 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;

}
4

1 回答 1

5

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

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

于 2012-04-07T16:17:58.100 回答