Help with getting last name using Structure with a loop

How can input the string for pname for array two using a structure elements

# include <iostream>
using namespace std;

So this code work , only holding the first name;
struct team
{
string pname;
int pnumber;
double pscore;
};


int main()
{
const int item=2;
team team1[item];
long int total=0;

for(int a=0; a<item; a++){
cout<<"Enter Player "<<a+1<<" Name\n";
cin>>team1[a].pname;
cout<<"Enter Player "<<a+1<<" Number\n";
cin>>team1[a].pnumber;
cout<<"Enter Player "<<a+1<<" Score\n";
cin>>team1[a].pscore;
total+=team1[a].pscore;


}

for(int b=0; b<item; b++){
cout<<"Name: "<<team1[b].pname<<endl;
cout<<"Player # : "<<team1[b].pnumber<<endl;
cout<<"Score : "<<team1[b].pscore<<endl;
cout<<endl;
}
cout<<endl<<"Team Final Score: "<<total;

return 0;

}




Enter Player 1 Name
Chris
Enter Player 1 Number
12
Enter Player 1 Score
30
Enter Player 2 Name
Tommy
Enter Player 2 Number
69
Enter Player 2 Score
30
Name: Chris
Player # : 12
Score : 30

Name: Tommy
Player # : 69
Score : 30


Team Final Score: 60
--------------------------------
Process exited with return value 0
Press any key to continue . . .


SO when i try getline(cin,team1[a].pname); it does not work, just skips the input for player 2


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

struct team
{
string pname;
int pnumber;
double pscore;
};


int main()
{
const int item=2;
team team1[item];
long int total=0;

for(int a=0; a<item; a++){
cout<<"Enter Player "<<a+1<<" Name\n";
getline(cin,team1[a].pname);
cout<<"Enter Player "<<a+1<<" Number\n";
cin>>team1[a].pnumber;
cout<<"Enter Player "<<a+1<<" Score\n";
cin>>team1[a].pscore;
total+=team1[a].pscore;


}

for(int b=0; b<item; b++){
cout<<"Name: "<<team1[b].pname<<endl;
cout<<"Player # : "<<team1[b].pnumber<<endl;
cout<<"Score : "<<team1[b].pscore<<endl;
cout<<endl;
}
cout<<endl<<"Team Final Score: "<<total;

return 0;

}








Enter Player 1 Name
Christopher Desir
Enter Player 1 Number
15
Enter Player 1 Score
30
Enter Player 2 Name
Enter Player 2 Number
15
Enter Player 2 Score
30
Name: Christopher Desir
Player # : 15
Score : 30

Name:
Player # : 15
Score : 30


Team Final Score: 60
--------------------------------
Process exited with return value 0
Press any key to continue . . .

You could see how it skips the input of player 2 name;

Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

http://www.cplusplus.com/reference/string/string/getline/

cin leaves a newline character('\n') in the stream, so when you call getline for the second player, no characters will be extracted as there is a '\n'.

To fix this, simply call cin.ignore( ) every time you use cin >>
http://www.cplusplus.com/reference/istream/istream/ignore/
Topic archived. No new replies allowed.