100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

getline() in C++

Learn how to use `getline()` to read entire lines of text including spaces, and avoid common pitfalls when mixing it with `cin >>`.

Input & OutputBeginner6 min readJul 7, 2026
Analogies

1. Intro

getline() is a function in the <string> header used to read an entire line of text from an input stream, including embedded spaces, until a newline character or a specified delimiter is encountered. It solves the limitation of cin >>, which stops reading at the first whitespace.

🏏

Cricket analogy: A commentator reading out a player's full nickname 'Mahi the Captain Cool' word-for-word, spaces included, is like getline() capturing an entire line, unlike cin >> which would stop at the first space.

2. Syntax

cpp
getline(cin, str);            // reads until newline
getline(cin, str, delimiter);  // reads until custom delimiter

3. Explanation

getline(cin, str) reads characters from cin into the string str until it encounters \n, which it consumes but does not store. An overloaded version, getline(cin, str, delim), reads until a custom delimiter character instead of the default newline. getline is essential whenever full sentences, names with spaces, or CSV-like fields need to be captured intact.

🏏

Cricket analogy: Reading a full over-by-over commentary line until the newline (which is consumed, not stored) is like getline(cin, str), while stopping instead at a comma to separate 'runs, wickets' fields is like the delimiter overload.

A classic gotcha: if cin >> var; is used before getline(cin, str);, the leftover newline character from the previous input stays in the buffer and is immediately consumed by getline, producing an empty string. Fix this by calling cin.ignore() after cin >> and before getline().

4. Example

cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    int age;
    string fullName;

    cout << "Enter age: ";
    cin >> age;
    cin.ignore(); // discard leftover newline

    cout << "Enter full name: ";
    getline(cin, fullName);

    cout << "Name: " << fullName << ", Age: " << age << endl;
    return 0;
}

5. Output

text
Enter age: 25
Enter full name: Maria Garcia
Name: Maria Garcia, Age: 25

6. Key Takeaways

  • getline(cin, str) reads an entire line, including spaces, unlike cin >> str.
  • The newline delimiter is consumed but not stored in the resulting string.
  • A custom delimiter can be supplied via getline(cin, str, delim).
  • Mixing cin >> and getline() requires cin.ignore() to discard a leftover newline.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#GetlineInC#Getline#Syntax#Explanation#Example#StudyNotes#SkillVeris#ExamPrep