Reputation: 2595
OK, I have this assignment and I have to prompt the user for data about 5 separate basketball players. My question prompts are in a for loop, the loop executes the first time for the first player fine, but when the second players info needs to be entered the first two question prompts are together on the same line, I have fiddled with this and just cannot figure it out, I am sure it is something small that I am apparently missing, thanks for any suggestions on how to fix this.
Here is the output:
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 *
Here is my code:
#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;
}
Upvotes: 2
Views: 186
Reputation: 490623
After you read a number (e.g., int
), there's still a new-line left in the input buffer that you haven't read. When you read another number, that skips across any white-space (including new-lines to find a number. When you read a string, however, the new-line in the input buffer is read as an empty string.
To make it work, you need to get the new-line out of the input buffer before you try to read the string.
Upvotes: 5