Mike9182
In Runtime
- Messages
- 258
- Location
- Altoona, PA
When the loop to get player data runs the second time it skips the name. What is wrong in it? I think it might have something to do with the keyboard buffer but I'm not sure.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
struct Player
{
char name[30];
int number;
int points;
};
int main()
{
// Get player data
Player data[12];
for (int i=0; i<12; i++)
{
cout << "Player " << (i+1) << endl;
cout << "Name: ";
cin.ignore();
cin.getline(data[i].name, 30);
cout << "Number: ";
cin >> data[i].number;
while (data[i].number < 0)
{
cout << "ERROR: Player cannot have negative number" << endl;
cout << "Number: ";
cin >> data[i].number;
}
cout << "Points: ";
cin >> data[i].points;
while (data[i].points < 0)
{
cout << "ERROR: Player cannot have negative points" << endl;
cout << "Points: ";
cin >> data[i].points;
}
cout << endl;
}
// Calculate team points
int teamPoints = 0;
for (int i=0; i<12; i++)
teamPoints += data[i].points;
// Find player with highest points
int highest = data[0].points;
int highestPoints = 0;
for (int i=1; i<12; i++)
{
if (highest < data[i].points)
{
highest = data[i].points;
highestPoints = i;
}
}
// Display output
cout << setw(25) << left << "Player" << setw(8) << left << "Number" << "Points" << endl;
for (int i=0; i<40; i++) cout << "-";
cout << endl;
for (int i=0; i<12; i++)
{
cout << setw(25) << left << data[i].name << setw(8) << left << data[i].number << data[i].points << endl;
}
cout << endl;
cout << "Team Points: " << teamPoints << endl;
cout << "High Scorer: #" << data[highestPoints].number << ", " << data[highestPoints].name << endl;
return 0;
}