getline in C++: Syntax, Examples & Use Cases

Learn via video courses
Topics Covered

You wrote cin >> name to read a user's name, and it only captured the first word. So you switched to getline(cin, name) and it worked. Then you tried using both in the same program, and getline skipped your input entirely. The variable came back empty, your program moved on, and you spent twenty minutes wondering what you did wrong.

You did nothing wrong. This is the single most common bug C++ students hit with input handling, and it happens because cin >> and getline() handle the input buffer differently. This page gives you the syntax, the fix for that bug, and every getline pattern you will actually use with runnable examples showing exact input and output for each one.

What Is getline() in C++? (Syntax First)

std::getline reads an entire line from an input stream into a std::string, including spaces. It stops when it encounters a newline character (or a custom delimiter you specify), consumes that delimiter from the stream, but does not store it in the string.

Syntax

istream& getline(istream& is, string& str, char delim);

  • is: the input stream (usually cin for console input)
  • str: the std::string variable where the line is stored
  • delim: optional — the character to stop at (defaults to \n)

Basic Example

Output:

This is why getline exists: cin >> stops reading at the first whitespace, so cin >> fullName with the same input would only capture "Rahul." The getline function reads until the newline, capturing everything.

Build an AI-First Career, Master the Complete Skillset

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program
NSDC Certified

AI Forward Deployed Engineer Program

Full-stack engineering, production AI and client-facing consulting

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program

The canonical reference for std::getline behavior is cppreference, which documents the exact stream-state semantics.

The Bug Everyone Hits: getline Skipped After cin >>

Here is the exact scenario. You ask the user for their age, then their name:

Input:

Actual Output:

The name is empty. getline did not wait for your input. It read something, but it was not "Rahul Sharma."

Why This Happens

When you type 25 and press Enter, the input buffer contains 25\n. The cin >> age reads the 25 but leaves the \n (newline character) sitting in the buffer. When getline(cin, name) runs next, it immediately sees that \n, treats it as an empty line, consumes it, and moves on. Your actual name input ("Rahul Sharma") is still in the buffer but getline has already returned.

The Fix: cin.ignore()

Call cin.ignore() between the cin >> and the getline to discard the leftover newline:

Input:

Output:

The Robust Fix

If there is a chance of extra whitespace or multiple characters left in the buffer (for example, the user typed "25 abc" and pressed Enter), use the numeric_limits variant to ignore everything up to the next newline:

cin.ignore(numeric_limits<streamsize>::max(), '\n');

This discards all characters in the buffer until it finds and consumes a \n. You need #include <limits> for this.

Sharpen Your Fundamentals with Free Learning

Reading With a Custom Delimiter

The third parameter of getline lets you stop at any character, not just \n. This is useful for parsing comma-separated input, semicolon-delimited data, or any custom format.

Comma-Separated Input

Input:

Output:

The last getline call uses the default \n delimiter, so it reads everything remaining on the line.

How Scaler Transformed Careers in Different Fields

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

getline() vs cin.getline(): string vs char Array

These two functions look similar but work with completely different types. Here is the comparison:

Featurestd::getline(cin, str)cin.getline(buffer, size)
Target typestd::stringchar array (C-style string)
Size limitNone — string resizes automaticallyFixed by the size parameter
Header<string><iostream>
Safe by defaultYes — no buffer overflow possibleNo — you must manage buffer size
Custom delimiterThird parameterThird parameter
Modern C++ recommendationUse this oneOnly for legacy code or specific C-string needs

cin.getline Example (Legacy Pattern)

Input:

Output:

The 50 is the maximum number of characters to read (including the null terminator). If the input exceeds the buffer size, cin.getline stops and sets the failbit. The cin.get() function is a related alternative that reads a single character at a time. For modern C++ code, use std::getline with std::string and avoid manual buffer management entirely. The guide on inputting strings in C++ covers when each approach makes sense.

Splitting Lines With stringstream

This is the pattern competitive programmers and production C++ code use to parse structured input: read a full line with getline, then split it using a stringstream and another getline with a custom delimiter.

Splitting CSV Data

Output:

The stringstream wraps the string as if it were an input stream. Then getline(ss, token, ',') reads from it field by field, stopping at each comma. The while loop continues until the stream is exhausted.

Splitting a Sentence Into Words

Output:

Note: this uses ss >> word (whitespace-delimited extraction) rather than getline, which is the simpler pattern for word splitting. For more advanced string splitting techniques in C++, the split string guide covers additional approaches including strtok, find/substr loops, and C++20's views::split.
For a broader reference on string operations in C++, including concatenation, comparison, and searching, the strings topic page covers the full std::string API.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Reading Until EOF and Practical Use Cases

Reading Multiple Lines Until End of File

Input (press Ctrl+D on Linux/Mac or Ctrl+Z on Windows after the last line):

Output:

The getline call returns the stream reference, which evaluates to true while the read succeeds and false at EOF. This makes it a clean loop condition with no extra flag variables.

Reading a File Line by Line

The same getline function works with file streams (ifstream) exactly as it works with cin. This is the standard pattern for processing text files in C++, whether you are reading configuration data, log files, or competitive programming input from a file.

Competitive Programming: Mixed Input Pattern

Input:

Output:

Practice C++ I/O patterns with structured exercises: Scaler's free C++ course covers input handling, string operations, and common debugging scenarios with hands-on problems. For a broader look at output handling, the cout reference covers formatting, precision control, and stream manipulators. Explore more in the C++ topics hub.

Master the fundamentals that make input bugs like this obvious. Scaler's Software Development Program builds your core programming and DSA skills with mentor-led guidance and placement support.


FAQs

What does getline() do in C++?

std::getline reads an entire line of text from an input stream into a std::string, including all spaces. It stops when it encounters a newline character (or a custom delimiter if you provide one as the third argument), consumes that delimiter from the stream, but does not include it in the resulting string. This makes it the standard way to read full sentences or lines with spaces, which cin >> cannot do because it stops at the first whitespace.

Why does getline() skip input after cin >>?

When cin >> reads a value like an integer, it leaves the newline character (\n) that you typed when pressing Enter sitting in the input buffer. The next getline call immediately encounters that leftover newline, treats it as an empty line, consumes it, and returns without waiting for new input. The fix is to call cin.ignore() between the cin >> and the getline to discard the leftover newline before getline runs.

What is the difference between getline() and cin.getline()?

std::getline works with std::string objects, which resize automatically and have no buffer overflow risk. cin.getline writes into a fixed-size char array and requires you to specify a maximum length, making it vulnerable to truncation if the input exceeds the buffer. In modern C++, std::getline is the recommended approach for almost all use cases. You will encounter cin.getline primarily in legacy codebases or in contexts that specifically require C-style character arrays.

Does getline() include the newline character in the string?

No. getline consumes the delimiter character (newline by default) from the input stream but does not append it to the string. If you read "Hello World\n" using getline(cin, str), the resulting string contains exactly "Hello World" with no trailing newline. This is consistent behavior across all standard library implementations as documented in cppreference.

How do I use getline() with a custom delimiter?

Pass the delimiter character as the third argument. For example, getline(cin, token, ',') reads input until it encounters a comma instead of a newline. This is commonly combined with stringstream to parse CSV-style input: you read a full line into a string, wrap it in a stringstream, then call getline(ss, token, ',') in a loop to extract each comma-separated field.

How do I read all lines from input until end of file?

Use getline as the condition of a while loop: while (getline(cin, line)) { ... }. The getline function returns a reference to the input stream, which evaluates to true while the read succeeds and false when it reaches EOF or encounters an error. This same pattern works with file streams by replacing cin with an ifstream object, making it the standard approach for processing text files line by line.