Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 171 ยท Getting Started

Reading User Input

Read numbers, words and whole lines in C++ with std::cin and std::getline, fix the leftover-newline bug, validate input and loop until input ends.

Programs become useful when they react to data they didn't know in advance: a name, a list of prices, an answer to a question. In C++ the standard way to read from the keyboard (or from any text piped into a program) is std::cin, the standard input stream, together with std::getline for whole lines.

Reading input looks easy, and the basics are. But input comes from humans, and humans type unexpected things. In this lesson you'll learn how >> really splits text, the famous "skipped getline" bug and its fix, how to detect bad input instead of silently using garbage, and how to process input until it runs out.

Using the Input box

In a real terminal, the program waits while you type. Our editors run your program on a server, so you type everything before pressing Run, in the Input box below the code. Each line in the box is one line of input, exactly as if you'd typed it and pressed Enter. The examples in this lesson come with input already filled in; change it and run again to see how the program reacts.

One visible difference: the text you "typed" isn't echoed in the output, so a prompt like Your name? is followed directly by the program's next output. In a terminal you'd see your typing in between.

Reading values with std::cin >>

std::cin lives in <iostream>. The extraction operator >> reads a value from it and stores it in a variable. The variable's type decides what is read: digits for an int, a decimal number for a double, one word for a std::string:

C++ Reading a word and numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The variables need to exist (be declared) before you read into them. Giving them a starting value like 0 is a good habit, as you'll see in Variables.

How >> splits the input

>> doesn't care about lines. For each read it:

  1. Skips any whitespace (spaces, tabs and line breaks).
  2. Reads characters as long as they fit the type: digits (and a sign) for an int, a number with an optional decimal point and exponent for a double, any non-whitespace characters for a std::string.
  3. Stops at the first character that doesn't fit, leaving it in the input for the next read.

So you can chain reads, and values can be on one line or spread over many:

C++ Several values on one line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The chain reads left to right, exactly like std::cout << writes left to right. Try putting each value on its own line in the Input box; the result is the same. Now try Ada Lovelace 3.9 4.5: the int read takes 3 and stops at the ., so the double read gets .9, and the price becomes 0.9. The stopping rule explains many "weird input" surprises.

Note: Because a std::string read with >> stops at whitespace, std::cin >> name can never read "Ada Lovelace" in one go. For text that may contain spaces, use std::getline.

Reading whole lines with std::getline

std::getline(std::cin, text) reads everything up to the end of the line, spaces included, into a std::string. The line break itself is consumed and thrown away, so it isn't part of text:

C++ Reading full lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

getline is in <string>. It reads an empty line as an empty string, which is often useful: an empty line can mean "no more entries".

The leftover newline bug

Mixing >> and getline is the most common input bug in C++. Run this program. The input box contains an age on the first line and a name on the second:

C++ getline seems to be skipped

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The name comes out empty: Age: 36, name: []. Here's why. The input is really the characters 36\nAda Lovelace\n. std::cin >> age reads 36 and stops at the line break, leaving it in the input. getline then reads up to the next line break, finds it immediately, and returns an empty line. The name is never read.

The fix is to skip that leftover whitespace before calling getline. The cleanest way is the std::ws manipulator, which discards all whitespace up to the next real character:

C++
std::cin >> age;
std::getline(std::cin >> std::ws, name);  // skip the leftover '\n' first

Change the getline line in the editor to this and run again; you'll get name: [Ada Lovelace]. Note that std::ws also skips empty lines, which is usually what you want here. If an empty line is meaningful input in your program, discard just the rest of the current line instead:

C++
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // needs <limits>

That line throws away every character up to and including the next '\n'.

Checking that input succeeded

What happens if the user types abc when you ask for a number? The read fails. std::cin sets its fail state, the variable is set to 0, and every later read on std::cin does nothing until you clear the error. If there's no input at all (the end of input was reached), the read also fails, and the variable keeps its old value.

A failed read doesn't throw an exception or stop the program, so you must check. The expression std::cin >> x gives back the stream itself, and a stream converts to true if it's still good:

C++ Detecting bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

With twelve as input, the read fails and the program reports an error with exit code 1. Change the input to 12 to see the success path. Also try 12 tickets: the read succeeds with 12, because >> stops at the space and leaves tickets unread. Whether that's acceptable depends on your program.

Asking again until the input is valid

To recover from a failed read and ask again, you need two steps: std::cin.clear() resets the fail state, and std::cin.ignore(...) throws away the bad line. Without ignore, the same bad characters would fail the next read too, forever:

C++ Retry until valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop uses while, if, continue and break, which you'll study in while and do-while Loops. The important part for now is the pattern: read, check, clear, ignore, try again. Notice the eof() check: when the input runs out completely, retrying can never succeed, so the program must stop instead of looping forever. Empty the Input box and run to see that branch.

Reading until the input ends

Often you don't know how many values are coming: a list of scores, the lines of a file. Put the read inside the loop condition. The loop runs as long as reads succeed and stops at the end of the input (or at the first value that isn't valid):

C++ Sum all the numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The same works line by line with getline, which is the standard way to process text input:

C++ Number every line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The empty line in the input is read as an empty string and numbered too. In a terminal, you'd end input by pressing Ctrl + D (Linux and macOS) or Ctrl + Z then Enter (Windows). When input comes from a file (program < data.txt), the end of the file ends the loop.

Warning: Don't write while (!std::cin.eof()) followed by a read. The end-of-file flag is only set after a read fails, so that loop runs one extra time and processes a value that was never read. Always put the read itself in the condition, as in the examples above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The input is Grace Hopper. What does std::cin >> name; store in the string name?

    >> reads a string only up to the first whitespace, so it gets Grace. Use std::getline to read the whole line.
  2. 2. The input is 25 then Grace Hopper on the next line. After std::cin >> age; std::getline(std::cin, name);, what is name?

    >> leaves the line break after 25 in the input, so getline reads an empty line. Use std::getline(std::cin >> std::ws, name).
  3. 3. The input is 7.8. What does int n = 0; std::cin >> n; store in n?

    An int read takes digits and stops at the first character that doesn't fit, here the .. So n is 7 and .8 stays in the input.
  4. 4. After a failed read, why do you need both std::cin.clear() and std::cin.ignore(...)?

    A stream in the fail state ignores all reads until you clear() it. The bad input is still waiting, so you also ignore() the rest of the line.
  5. 5. With the input 3 5 x 9, what does while (std::cin >> v) sum += v; leave in sum (starting at 0)?

    The loop adds 3 and 5, then the read of x fails, which ends the loop. The 9 is never read.

Summary

  • std::cin >> variable reads one value; the variable's type decides what counts as valid input.
  • >> skips leading whitespace, reads as much as fits, and leaves the rest (including line breaks) for the next read.
  • std::getline(std::cin, text) reads a whole line, spaces included, without the line break.
  • After >>, use std::getline(std::cin >> std::ws, text) to avoid the leftover-newline bug.
  • Always check reads: if (std::cin >> x). A failed read sets the fail state; recover with clear() plus ignore(), and stop at end of input.
  • Loop with the read in the condition, while (std::cin >> x) or while (std::getline(std::cin, line)), to process all input.
  • In our editors, type the input in the Input box before pressing Run.

Next: Keywords and Identifiers, where you'll learn C++'s reserved words and the rules for naming things.