Console Input and Output

Reading Full Lines with std::getline

The extraction operator >> reads a single word, then it stops. Spaces are delimiters, so anything else on the current line is left in the input. When a program needs to read a full line, including any spaces it may contain, std::getline is the way to go.

We will treat the type std::string as a black box for now. It's a container that can hold a sequence of characters, and we'll see exactly how that works later. For the moment, just know that a std::string can store the contents that std::getline reads.

A bare minimum program that reads a single line of text and then writes it back to the user is shown below.

#include <iostream>
#include <string>

int main()
{
    std::string line{};
    // Read the whole line, including spaces
    std::getline(std::cin, line);
    std::cout << line << '\n';
    return 0;
}

The variable line is initially an empty std::string. The function call std::getline(std::cin, line) reads characters from the standard input stream until it reaches a newline character. Every character it reads before the newline is stored in line; the newline character is removed from the stream and discarded.

The insertion statement then prints the contents of line to the console, reproducing exactly the text the user typed, spaces included.

For example, a sentence like hello there world is stored and printed.

The same function can be used to read multiple lines. Each call to std::getline pulls a single line out of the stream and leaves the next line ready for the next call.

#include <iostream>
#include <string>

int main()
{
    std::string first{};
    std::string second{};

    // Extract formatted input into the target variable
    std::getline(std::cin, first);
    std::getline(std::cin, second);

    std::cout << first << '\n';
    std::cout << second << '\n';
    return 0;
}

The first std::getline reads the first line entered and puts it in first. The second std::getline reads the next line and puts it in second. The two insertion statements then print both lines back to the console in their original order. The result is two echoed input lines, space including.

A common pitfall is mixing extraction with >> and std::getline. When >> is used to read in data, the extraction operation leaves the newline character still on the input stream. When std::getline is called afterwards, it reads the leftover newline character, and ends up storing an empty string.

#include <iostream>
#include <string>

int main()
{
    int number{};
    std::string line{};

    std::cin >> number;
    std::getline(std::cin, line);

    std::cout << number << '\n';
    std::cout << line << '\n';
    return 0;
}

After the user enters a number, such as 1234, std::cin >> number takes only the digits. The newline is left sitting in the stream. std::getline then tries to read a line, and immediately reads the pending newline. It returns, and the variable line is empty.

So, the next insertion statement prints a blank line.

The number is printed, and what the user intended to enter for the line of text is lost.

A simple solution is just to read an extra line, and discard it.

#include <iostream>
#include <string>

int main()
{
    int number{};
    std::string line{};

    std::cin >> number;
    std::getline(std::cin, line);   // consume the leftover newline
    std::getline(std::cin, line);   // now read the real line

    std::cout << number << '\n';
    std::cout << line << '\n';
    return 0;
}

The first call to std::getline grabs the extra pending newline, and the empty string it produces is simply ignored. The second call then reads in the actual line of input that the user entered. Both the number and the desired line are now available in the program.

So, std::getline provides a simple way to read a whole line at a time, spaces and all. The destination is a std::string, and each call reads a single line. Just be aware of the leftover newline issue when mixing >> with std::getline and remember to account for it, and your program will be able to accept whole sentences and names containing spaces.

Exercise: Reading Full Lines with std::getlineStarter code, hints and solutionOpenClose
Guided practiceBeginner · 10–15 min

Practice: Reading Full Lines with std::getline

Work through the mission, reveal hints only when needed, and compare your result with the model solution.

Your challenge

Use red apple and blue sky as two input lines. Label the output as first and second and explain how spaces and line endings are handled.

Mission checklist

  1. Run the starter as a baseline, then predict the change requested in Your challenge.
  2. Make that change in your editor; use the lesson-specific hints if you need help.
  3. Compile and run your answer, then compare with the worked solution and explain the result.

Starter program

This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.

#include <iostream>
#include <string>

int main()
{
    std::string first{};
    std::string second{};

    // Extract formatted input into the target variable
    std::getline(std::cin, first);
    std::getline(std::cin, second);

    std::cout << first << '\n';
    std::cout << second << '\n';
    return 0;
}

Hints

Hint 1

Each getline call consumes one whole line, including spaces in its text, and removes the terminating newline from the input stream.

Hint 2

Enter a two-word first line and a different second line. first and second store separate lines; pressing Enter on an empty line produces an empty string.

Worked solution

For the two sample lines, first receives red apple and second receives blue sky. getline retains the spaces within each line. The output labels make the variable-to-input mapping explicit.

#include <iostream>
#include <string>

int main()
{
    std::string first{};
    std::string second{};

    // Extract formatted input into the target variable
    std::getline(std::cin, first);
    std::getline(std::cin, second);

    std::cout << "first = " << first << '\n';
    std::cout << "second = " << second << '\n';
    return 0;
}

Example input

red apple
blue sky

Example output

Program output only; your terminal may also echo the input you type.

first = red apple
second = blue sky

0 comments

No comments yet. Be the first.

Add a comment

About CppLearn

CppLearn is an interactive, free reference for modern C++. In each lesson, you'll find out how the language works, rather than just lines of code that you can copy and paste. We cover concepts starting from beginner lessons on fundamentals and proceed to templates, move semantics, smart pointers, and areas that usually trap or scare C++ learners.