Reading a Whole Line
cin >> text reads a single word: it stops at the first space. To read everything the user typed up to the Enter key, spaces included, use std::getline from the <string> header:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Full name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
}
Typing Ada Lovelace prints Hello, Ada Lovelace!. With std::cin >> name it would print Hello, Ada! and leave Lovelace waiting in the input.
The signature is:
std::istream& std::getline(std::istream& input, std::string& text);
std::istream& std::getline(std::istream& input, std::string& text, char delim);
inputis any input stream:std::cin, a file opened withstd::ifstream, or astd::istringstreambuilt from a string.textis replaced (not appended to) with the characters read.delimis the character that ends the read. It defaults to'\n'. The delimiter is removed from the stream and is not stored intext.- The return value is the stream itself, which is what lets you test it in a condition.
Because getline works the same on every input stream, the runnable examples on this page read from a std::istringstream holding fixed text. That makes the output predictable without typing anything. To read from the keyboard instead, replace the stream variable with std::cin.
Output:
[Ada Lovelace]
[Alan Turing]
The brackets show that the newline is not part of either string.
getline After cin >> Returns an Empty String
This is the most common getline problem. You read a number with >>, then a line with getline, and the getline seems to be skipped:
Output:
age: 30
city: []
input >> age reads the characters 30 and stops at the first character that cannot be part of a number, the newline. That newline stays in the stream. getline then reads up to the next newline, finds one immediately, and returns an empty string. With std::cin the effect is that the program never pauses for the second answer.
There are two standard fixes. Both go between the >> and the getline.
Fix 1: discard the rest of the line with ignore.
Output:
age: 30
city: [Paris]
ignore(n, '\n') throws away characters until it has removed a newline or n characters, whichever comes first. Passing the largest possible std::streamsize means "until the newline, however far away". It also removes anything the user typed after the number on the same line, such as trailing spaces. With the keyboard the line is std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');, and it needs #include <limits>.
A bare std::cin.ignore() discards exactly one character. It works when the newline follows the number directly, and fails as soon as there is a space before it.
Fix 2: skip leading whitespace with std::ws.
Output:
age: 30
city: [Paris]
std::ws is a manipulator that consumes all whitespace (spaces, tabs, newlines) at the current position. input >> std::ws returns the stream, so it can go straight into getline. It also skips blank lines and leading spaces, which is convenient for names and cities but wrong when leading spaces or an empty line are meaningful input. In that case use ignore.
Reading Until the End of Input
getline returns the stream, and a stream converts to false once a read fails. When there are no more lines, getline fails, so a while loop around it reads every line and stops at the end:
Output:
1: [apples 3]
2: [bread 1]
3: []
4: [milk 2]
read 4 lines
Two details from that output:
- An empty line is still a successful read. It gives an empty string and the loop continues. Only reaching the end of the input stops it.
- The last line does not need a trailing newline. If the text ended with
milk 2and no\n,getlinewould still return it, and the next call would fail.
With std::cin, the same loop reads until the input ends. That happens when input is piped from a file (./program < data.txt), or when the user presses Ctrl+D on macOS and Linux, or Ctrl+Z then Enter on Windows.
Avoid the pattern while (!input.eof()) { std::getline(input, line); ... }. eof() only becomes true after a read has already hit the end, so the body runs one extra time with a failed read and a stale line. Put the getline call in the condition instead.
Reading a File Line by Line
Files use the same loop. Open the file with std::ifstream from <fstream>, check that it opened, and read:
Output:
1. Ada 92
2. Grace 88
3. Alan 95
if (!file) catches a missing file or a wrong path before the loop. Without it, the loop simply reads zero lines, which looks like an empty file rather than an error. The file closes automatically when file goes out of scope at the end of main.
Files saved on Windows end each line with \r\n. When such a file is read on Linux or macOS, getline removes the \n but keeps the \r, so every line ends with an invisible carriage return that breaks comparisons like line == "done". Strip it after reading:
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
Using a Custom Delimiter
The third argument changes the character that ends each read. A common use is splitting one line on commas. Read the line first, then split it through a std::istringstream:
Output:
fields: 3
[Ada Lovelace]
[36]
[London]
The comma is removed from the stream and not stored, the same way the newline is in the default form. Note that with a custom delimiter a newline is an ordinary character. If you call std::getline(file, field, ',') directly on a multi-line file, the last field of one line and the first field of the next come back joined together, as in "London\nGrace Hopper". Reading one line at a time and splitting each line separately avoids that. The string streams page covers std::istringstream in more detail, including converting fields such as "36" to numbers.
std::getline vs cin.getline
There is also a member function with a similar name:
char buffer[20];
std::cin.getline(buffer, 20); // member function, fixed-size char array
std::string text;
std::getline(std::cin, text); // free function, std::string
cin.getline writes into a char array and stores at most size - 1 characters plus the terminating '\0'. A longer line puts the stream into a failed state, and every later read is skipped until you call std::cin.clear(). std::getline with a std::string has no length limit to manage. Use it unless you are working with an API that requires a char array.
Common Mistakes
- Mixing
>>andgetlinewithout clearing the newline. Addignore(...)or usestd::wsbetween them. The input and output page shows the same issue withstd::cinand how to recover when a numeric read fails. - Calling
getline(std::cin, number)with anint.getlineonly reads into astd::string. Read the line, then convert withstd::stoior astd::istringstream. - Looping on
eof(). Test thegetlinecall itself:while (std::getline(input, line)). - Forgetting
#include <string>.std::getlinefor strings is declared in<string>. Some compilers let it slip through via<iostream>, and the code then fails on another compiler. - Not checking that a file opened. A wrong path makes
std::ifstreamfail silently and the read loop run zero times.
Frequently Asked Questions
What does getline do in C++?
std::getline(stream, text) reads characters from stream into the std::string text until it reaches a newline, then removes that newline from the stream without storing it. Unlike cin >> text, it keeps spaces, so it reads a whole line such as a full name or a sentence.
Why is getline skipped after cin >> in C++?
cin >> number stops reading at the newline you typed after the number and leaves that newline in the input buffer. The next getline finds it immediately and returns an empty string. Discard it first with std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');, or call std::getline(std::cin >> std::ws, text) to skip leading whitespace.
How do I use getline with a delimiter other than newline?
Pass the delimiter as a third argument: std::getline(stream, field, ','). It reads up to the next comma, stores the text before it, and discards the comma. Newlines are then treated as ordinary characters, so this is usually combined with a std::stringstream built from a single line.
How do I read a file line by line in C++?
Open it with std::ifstream file("data.txt"); and loop with while (std::getline(file, line)) { ... }. getline returns the stream, which converts to false once there are no more lines, so the loop stops at end of file.
What is the difference between cin.getline and getline?
std::getline(std::cin, text) is a free function that reads into a std::string, which grows to fit any line. std::cin.getline(buffer, size) is a member function that reads into a fixed char array and fails if the line is longer than size - 1 characters. Use std::getline with std::string unless you have a reason to use raw arrays.