Skip to content

The getline trap

Watch it run · 1 of 3

Where did the name go?

1#include <iostream>
2#include <string>
3using namespace std;
4
5int main() {
6 int age;
7 string name;
8 cin >> age;
9 getline(cin, name);
10 cout << "[" << name << "]" << endl;
11 return 0;
12}

Memory

int age

21

string name

""

Typed input

21
Asha Patil

Output

(nothing yet)

line 8cin >> age reads 21 but leaves the end of that line (the Enter key) behind.

step 1 of 3