Problem with player's name when creating game.

I'm creating a simple hangman game in c++ and in the beginning the program asks the player for his/her name. I've declared the variable 'name' as a string and it works when the name is e.g. Piper, but if the player writes e.g. Piper Green, then the program flips out completely. How can I make this work?

1
2
3
4
5
6
7
  #include <iostream>
  using namespace std;
  string name;
  
  cout<<"What is your name?"<<endl;
  cin>>name;
  cout<<"Hi, "<<name<<". Let's play hangman."<<endl;
From the description of string's >> operator:
Notice that the istream extraction operations use whitespaces as separators; Therefore, this operation will only extract what can be considered a word from the stream. To extract entire lines of text, see the string overload of global function getline.

Last edited on
when you do cin >> name,
compiler only gets all the characters until 'space' or 'newline'. And it ignores everything after the space.
So you the getline function to get the whole line
1
2
cout << "Whats is your name?" << endl;
getline(cin, name);


This will use cin, but it will get everything and store it in string name.
Thanks to both of you, it works now! I had to add a cin.ignore() as well, not sure why yet (trying to find the answer through google atm).
I had to add a cin.ignore() as well, not sure why yet (trying to find the answer through google atm).
Maybe this would help: http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction
Topic archived. No new replies allowed.