All lessons
LESSON 19/53Text and Array
Reading a Whole Line
GOALRead a whole sentence, spaces included.

cin >> s stops at the first SPACE. Type "Bat Erdene" and you only get "Bat". For the whole line use getline.
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
string first;
cin >> first; // reads one word
string rest;
getline(cin, rest); // reads the rest of the line
cout << "Word: " << first << endl;
cout << "Rest:" << rest << endl;
return 0;
}> what you see
(input: Bat Erdene Suh) Word: Bat Rest: Erdene Suh
//LINE BY LINE
Watch it run
You type Bat Erdene Suh and press Enter. The line waits in a queue.
Mixing cin >> and getline
This is the trap that catches everyone. cin >> n reads the number but leaves the new-line behind. The next getline then reads that empty line.
Wrong:
int n;
cin >> n;
string name;
getline(cin, name); // ✗ хоосон мөр уншина!Right — add cin.ignore():
int n;
cin >> n;
cin.ignore(); // ← үлдсэн шинэ мөрийг хая
string name;
getline(cin, name); // ✓ одоо зөв ажиллана