Menu

C++ Input and Output: cin, cout, getline, and Streams

How console I/O works in C++ - printing with cout, reading with cin, the classic getline-after-cin newline bug, and how to recover when input fails.

This page includes runnable editors - edit, run, and see output instantly.

How C++ Talks to the Console

C++ does console I/O through streams from the <iostream> header. You write to the world with cout (character output) and read from the user with cin (character input). They use two operators you've already seen as bit-shifts, repurposed here:

  • << is the insertion operator - it sends data into cout.
  • >> is the extraction operator - it pulls data out of cin into a variable.

A handy way to remember the direction: the arrows point the way the data flows. Now that you can hold text in strings, let's move that text in and out of your program.

Printing with cout

cout sends whatever you insert to standard output. You can chain multiple << in one statement, mixing text, numbers, and variables freely.

Each << appends to the same line until you insert a newline. You have two ways to do that: '\n' inserts a newline character, while endl inserts a newline and flushes the buffer to the screen. Flushing has a real cost, so inside a loop that prints thousands of lines, prefer '\n' - the stream flushes on its own when needed (and always at program exit).

// Fine for a one-off message:
cout << "Done" << endl;

// In a hot loop, prefer this - no forced flush each iteration:
for (int i = 0; i < 1000000; ++i)
    cout << i << '\n';

Reading with cin and >>

cin >> variable reads one whitespace-delimited token and converts it to the variable's type. It skips any leading spaces or newlines, then stops at the next whitespace.

Because >> stops at whitespace, it's great for individual numbers and single words but useless for a full sentence: cin >> word on the input hello world reads only hello and leaves world in the buffer for the next read.

Reading a Full Line with getline

To capture an entire line - spaces and all - use getline(cin, line), which reads everything up to the Enter key into a std::string.

This is the right tool whenever the input can contain spaces - names, addresses, sentences. There's just one trap waiting for you the moment you mix getline with >>.

The cin + getline Newline Trap

This is the single most common C++ I/O bug. When you do cin >> n, the extraction reads the number but leaves the newline (the Enter key you pressed) sitting in the input buffer. The next getline sees that leftover newline immediately, treats the line as already finished, and hands you an empty string - without ever pausing for input.

int age;
string city;

cin >> age;            // you type 30 and press Enter; '\n' stays in the buffer
getline(cin, city);    // reads the leftover '\n' -> city is "" (empty!)

The fix is to discard that leftover newline with cin.ignore after the >> and before the getline:

cin.ignore(numeric_limits<streamsize>::max(), '\n') skips characters until it has eaten a newline (or hit end-of-input). It's the robust version - the shorter cin.ignore() only discards a single character, which breaks if the user typed extra spaces after the number. Reach for the full form by habit.

When Input Fails

If the user types letters where you expected a number, the extraction fails: cin enters an error state and the target variable is left unchanged (set to 0 since C++11). Worse, once cin is in a failed state, every later read is silently skipped too, so you can end up in an infinite loop.

The recovery is always two steps: cin.clear() resets the error flags so the stream is usable again, and cin.ignore(...) throws away the offending characters that are still stuck in the buffer. Skip the ignore and the bad input stays put, so the next >> fails again - the classic infinite loop. Checking cin >> n directly in the condition works because the stream converts to false when it's in a failed state.

Common Mistakes to Avoid

  • Using cin >> s for a sentence. It stops at the first space. Use getline for anything with spaces.
  • Forgetting cin.ignore between >> and getline. The leftover newline gives you an empty line. Clear the buffer first.
  • Reaching for endl everywhere. Each one forces a flush. Default to '\n' and save endl for when output truly must appear now.
  • Ignoring a failed cin. Letters in a numeric read leave cin broken; always clear() then ignore() before reading again.

Next: String Streams

Console I/O and string handling come together in string streams. A stringstream gives you the same << and >> operators, but pointed at an in-memory string instead of the console - perfect for parsing a line into numbers, building up formatted text, and converting between strings and other types without ever touching the keyboard.

Frequently Asked Questions

Why does getline skip the input right after using cin in C++?

cin >> x reads the number but leaves the newline you pressed sitting in the buffer. The next getline reads up to that leftover newline and returns an empty string immediately. Clear it first with cin.ignore(numeric_limits<streamsize>::max(), '\n'); after the >> and before the getline.

What is the difference between endl and \n in C++?

Both end the line, but endl also flushes the output buffer to the screen, while '\n' just inserts a newline. The flush has a cost - in a tight loop, prefer '\n' and let the stream flush on its own. Use endl only when you genuinely need the output to appear right now.

How do I read a whole line of text including spaces in C++?

Use getline(cin, line), not cin >> line. The >> operator stops at the first whitespace, so it only grabs one word. getline reads everything up to the Enter key into a std::string, spaces included.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED