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>
usingnamespace std;
string name;
cout<<"What is your name?"<<endl;
cin>>name;
cout<<"Hi, "<<name<<". Let's play hangman."<<endl;
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.
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.