Loading lessons...
User Input Strings (getline)
User Input Strings (getline)
Reading a whole sentence takes more than cin >>. Learn when each tool is right.
cin >> reads one word
string name;
cin >> name;
If the user types Ada Lovelace, only Ada lands in name. Extraction stops at the first whitespace.
getline reads a full line
#include <string>
string sentence;
getline(cin, sentence);
std::getline(cin, sentence) reads everything up to the newline, spaces included. Perfect for full sentences.
The mixing gotcha
int age;
string name;
cout << "Age: ";
cin >> age;
cout << "Name: ";
getline(cin, name); // name is empty!
cin >> age leaves the newline behind. getline then reads that leftover newline and stops instantly, so name comes out empty.
The fix
cin >> age;
cin.ignore(); // eat the leftover newline
getline(cin, name);
Or use getline for everything and convert with stoi. Know who owns the newline and you will be fine.
TL;DR
cin >>reads one whitespace-separated word.getline(cin, s)reads a full line including spaces.- Mixing
cin >>thengetlineleaves a stray newline. - Use
cin.ignore()to discard it.