C++ · Module 3 · Lesson 21 min read

Reading Full Lines with getline

std::getline

c
std::string full_name;
std::getline(std::cin, full_name);   // reads the WHOLE line, including spaces
  • Reads until the newline '\n'
  • The newline is removed (not stored in the string)
  • Returns the stream, so while (std::getline(std::cin, line)) reads every line

The famous >> + getline trap ⚠️

c
int age;
std::string name;
std::cin >> age;               // user types: 25<Enter>
std::getline(std::cin, name);  // reads the leftover '\n' → name is EMPTY!

>> reads 25 but leaves the newline in the buffer. getline sees it immediately and returns an empty line.

Fixes

c
std::cin >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // discard rest of line ✅
std::getline(std::cin, name);

or use std::getline(std::cin >> std::ws, name); — std::ws skips leading whitespace (including the newline).

Custom delimiter

c
std::getline(std::cin, field, ',');   // read up to a comma

Useful for simple CSV parsing.

Reading a line, then parsing it

A robust pattern: read every input as a line, then convert:

c
std::string line;
std::getline(std::cin, line);
int age = std::stoi(line);

(Validation in lesson 3.4.)

Checking for empty input

arduino
if (line.empty()) { /* user just pressed Enter */ }

Example

C++
#include <iostream>
#include <limits>
#include <string>

int main() {
    int age;
    std::string full_name, address, note;

    std::cout << "Age: ";
    std::cin >> age;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');   // drop the leftover newline

    std::cout << "Full name: ";
    std::getline(std::cin, full_name);
    std::cout << "Address: ";
    std::getline(std::cin, address);

    std::cout << "\nName: " << full_name << " (" << full_name.size() << " characters)\n";
    std::cout << "Age: " << age << ", Address: " << address << '\n';

    std::cout << "Tags (comma separated): ";
    std::string tag;
    int n = 0;
    while (std::getline(std::cin, tag, ',')) {           // custom delimiter
        if (!tag.empty() && tag.back() == '\n') tag.pop_back();
        std::cout << "\n  tag " << ++n << ": [" << tag << "]";
    }
    std::cout << '\n';
    return 0;
}

/* Output:
Age: Full name: Address:
Name: Asha Kumari Sharma (18 characters)
Age: 24, Address: Lakeside, Pokhara
Tags (comma separated):
  tag 1: [food]
  tag 2: [rent]
  tag 3: [travel]
*/