getline reads everything
To read a full line – including spaces – use getline(cin, variable):
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Full name: ";
getline(cin, fullName);
cout << "Hello, " << fullName << "!\n";
return 0;
}Input (what the user types)
Arjun Mehta
Output
Full name: Hello, Arjun Mehta!
Mixing cin >> and getline
There is one famous trap. After cin >> reads a number, the Enter key the user pressed is still waiting. A getline straight after reads that empty leftover line instead of the real text.
The fix: call cin.ignore() to throw that leftover Enter away before getline:
#include <iostream>
#include <string>
using namespace std;
int main() {
int age;
string city;
cout << "Age: ";
cin >> age;
cin.ignore(); // throw away the Enter after the number
cout << "City: ";
getline(cin, city);
cout << age << " years old, living in " << city << "\n";
return 0;
}Input (what the user types)
30 New Delhi
Output
Age: City: 30 years old, living in New Delhi
Remember: Going from
cin >>togetline? Putcin.ignore();in between.