getline(cin, string) is giving me a weird glith

Pretty much I am asking the user for how many people are playing. After that I use a vector to make a class for each player. I then ask them for the name of each player. I use a for loop which takes int i<the_vector.size(), but for some reason when I use getline it stores one of the names as a blank. With cin>> it works perfectly fine, but I only get the first word with no spaces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	void multi_fight()
              {
		cout<<"Hello\n";
		for(int i=0; i<players.size();i++)
	 	{
			//In the code it will display this text twice, and after 
                       //that is will display the names with one blank in the beginning                             
                        cout<<"Please enter in the names of the players"<<endl;
			getline(cin, players[i].name);
		}
		for(int C=0; C<players.size(); C++)
		{
			cout<<players[C].name<<endl;
		}
		system("pause");
	}



I don't know if this has anything to do with it but

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void multi_data()
	{
		int num_players;
		while(true){
		system("cls");
		cout<<"How many people will be playing?"<<endl;
		cin>>num_players;
		if(num_players==1)
		{
			cout<<"You can't choose only 1 player in Multi-Player"<<endl;
			system("pause");
			system("cls");
		}
		else
		{
			break;
		}
		}


		for(int i=0; i<num_players; i++)
		{
			players.push_back(fighter());
		}
	}
Last edited on
When executing this line:
cin>>num_players;
the program skips leading whitespace and then reads every digit from the input, and not a byte more. You pressed enter after entering those digits, and the endline character is still waiting to be processed. If you used another cin >>, it would skip over that endline because it skips over leading whitespace (and endline is a form of whitespace)

When executing this line:
getline(cin, players[i].name);
the program *doesn't* skip whitespace: it reads every character from the input up to and including the next endline. There is an endline already, so, exactly as you said,
it stores one of the names as a blank.


This is a common stumble for the beginners: after cin >> and before getline(), you have to dispose of the endline character:
cin.ignore(); will do just that (ignore one character)

In case someone entered a bunch of junk after the number of players and before hitting enter, you may want to use the ultimate ignore:
cin.ignore(numeric_limits<streamsize>::max(), '\n' );
Last edited on
Topic archived. No new replies allowed.