1.5 — Introduction to iostream: cout, cin, and endl

In this lesson, we’ll talk more about std::cout, which we used in our Hello world! program to output the text Hello world! to the console. We’ll also explore how to get input from the user, which we will use to make our programs more interactive.

The input/output library

The input/output library (io library) is part of the C++ standard library that deals with basic input and output. We’ll use the functionality in this library to get input from the keyboard and output data to the console. The io part of iostream stands for input/output.

To use the functionality defined within the iostream library, we need to include the iostream header at the top of any code file that uses the content defined in iostream, like so:


The iostream library contains a few predefined variables for us to use. One of the most useful is std::cout, which allows us to send data to the console to be printed as text. cout stands for “character output”.

As a reminder, here’s our Hello world program:

In this program, we have included iostream so that we have access to std::cout. Inside our main function, we use std::cout, along with the insertion operator (<<), to send the text Hello world! to the console to be printed.

std::cout can not only print text, it can also print numbers:

This produces the result:


It can also be used to print the value of variables:

This produces the result:


To print more than one thing on the same line, the insertion operator (<<) can be used multiple times in a single statement to concatenate (link together) multiple pieces of output. For example:

This program prints:

Hello world!

Here’s another example where we print both text and the value of a variable in the same statement:

This program prints:

x is equal to: 5


What would you expect this program to print?

You might be surprised at the result:

Hi!My name is Alex.

Separate output statements don’t result in separate lines of output on the console.

If we want to print separate lines of output to the console, we need to tell the console when to move the cursor to the next line.

One way to do that is to use std::endl. When output with std::cout, std::endl prints a newline character to the console (causing the cursor to go to the start of the next line). In this context, endl stands for “end line”.

For example:

This prints:

My name is Alex.


In the above program, the second std::endl isn’t technically necessary, since the program ends immediately afterward. However, it serves two useful purposes: First, it helps indicate that the line of output is a “complete thought”. Second, if we later want to add additional output statements, we don’t have to modify the existing code. We can just add them.

std::endl vs ‘\n’

Using std::endl can be a bit inefficient, as it actually does two jobs: it moves the cursor to the next line, and it “flushes” the output (makes sure that it shows up on the screen immediately). When writing text to the console using std::cout, std::cout usually flushes output anyway (and if it doesn’t, it usually doesn’t matter), so having std::endl flush is rarely important.

Because of this, use of the ‘\n’ character is typically preferred instead. The ‘\n’ character moves the cursor to the next line, but doesn’t do the redundant flush, so it performs better. The ‘\n’ character also tends to be easier to read since it’s both shorter and can be embedded into existing text.

Here’s an example that uses ‘\n’ in two different ways:

This prints:

x is equal to: 5
And that's all, folks!

Note that when ‘\n’ is used by itself to move the cursor to the next line, the single quotes are needed. When embedded into text that is already double-quoted, the single quotes aren’t needed.

We’ll cover what ‘\n’ is in more detail when we get to the lesson on chars (4.11 -- Chars).

Best practice

Prefer ‘\n’ over std::endl when outputting text to the console.


‘\n’ uses a backslash (as do all special characters in C++), not a forward slash. Using a forward slash (e.g. ‘/n’) instead may result in unexpected behavior.


std::cin is another predefined variable that is defined in the iostream library. Whereas std::cout prints data to the console using the insertion operator (<<), std::cin (which stands for “character input”) reads input from keyboard using the extraction operator (>>). The input must be stored in a variable to be used.

Try compiling this program and running it for yourself. When you run the program, line 5 will print “Enter a number: “. When the code gets to line 7, your program will wait for you to enter input. Once you enter a number (and press enter), the number you enter will be assigned to variable x. Finally, on line 8, the program will print “You entered ” followed by the number you just entered.

For example (I entered 4):

Enter a number: 4
You entered 4

This is an easy way to get keyboard input from the user, and we will use it in many of our examples going forward. Note that you don’t need to use ‘\n’ when accepting input, as the user will need to press the enter key to have their input accepted, and this will move the cursor to the next line.

If your screen closes immediately after entering a number, please see lesson 0.8 -- A few common C++ problems for a solution.

Best practice

There’s some debate over whether it’s necessary to initialize a variable immediately before you give it a user provided value via another source (e.g. std::cin), since the user-provided value will just overwrite the initialization value. In line with our previous recommendation that variables should always be initialized, best practice is to initialize the variable first.

We’ll discuss how std::cin handles invalid input in a future lesson (5.10 -- std::cin, extraction, and dealing with invalid text input).

For advanced readers

The C++ io library does not provide a way to accept keyboard input without the user having to press enter. If this is something you desire, you’ll have to use a third party library. For console applications, we’d recommend the pdcurses library. Many graphical user libraries have their own functions to do this kind of thing.


New programmers often mix up std::cin, std::cout, the insertion operator (<<) and the extraction operator (>>). Here’s an easy way to remember:

  • std::cin and std::cout always go on the left-hand side of the statement.
  • std::cout is used to output a value (cout = character output)
  • std::cin is used to get an input value (cin = character input)
  • << is used with std::cout, and shows the direction that data is moving (if std::cout represents the console, the output data is moving from the variable to the console). std::cout << 4 moves the value of 4 to the console
  • >> is used with std::cin, and shows the direction that data is moving (if std::cin represents the keyboard, the input data is moving from the keyboard to the variable). std::cin >> x moves the value the user entered from the keyboard into x

We'll talk more about operators in lesson 1.8 -- Introduction to literals and operators.

Quiz time

Question #1

Consider the following program that we used above:

The program expects you to enter an integer value, as the variable x that the user input will be put into is an integer variable.

Run this program multiple times and describe what happens when you enter the following types of input instead:

a) A letter, such as h

Show Solution

b) A number with a fractional component. Try numbers with fractional components less than 0.5 and greater than 0.5 (e.g. 3.2 and 3.7).

Show Solution

c) A small negative integer, such as -3

Show Solution

d) A word, such as Hello

Show Solution

e) A really big number (at least 3 billion)

Show Solution

The last suggestion may be particularly surprising. Try it! This happens because x can only hold numbers up to a certain size. After that, it "overflows". We'll discuss overflow in a future lesson.

1.6 -- Uninitialized variables and undefined behavior
1.4 -- Variable assignment and initialization

357 comments to 1.5 — Introduction to iostream: cout, cin, and endl

  • jason

    what can be added to the back of "int"? I add a number after it,and fail to programme,but i succeed when i add chinese character after it. why is this

    • nascardriver

      Variable names must begin with a letter (Chinese is allowed, please use ASCII) or an underscore (Special rules apply to identifiers beginning in an underscore, so avoid those).

  • Anonymous

    What does 'flushing the buffer' mean, and why does doing it after every newline add performance issues?

    Is '\n' preferred over "\n" when used standalone and "\n" over '\n' while it is already part of a string?

    Also, is it then advisable to use std::endl at the end of a file or program over '\n' or "\n" as it 'flushes the buffer'?

    • nascardriver

      When you send something to a `cout` it's not printed immediately but stored in memory until some time later.
      By using `endl`, you're forcing `count` to print the text now (That's "flushing"), rather than later. Printing is slow. The less often you print, the better.

      You don't need flush manually unless you really need the text to be printed at that point (eg. because it's some important long message or `cout` fails to flush automatically (can happen in loops)). `count` flushes automatically when the stream is closed.

      '\n' for standalone, "hello\n" when it's a string.

      • Anonymous

        Thanks for the response!

        What I still don't understand is what is meant by printing text "immediately".


        > `cout` flushes automatically when the stream is closed.

        What is meant by "when the stream is closed" ?

        As an unimportant side-question, was the option to edit replies for upto an hour after replying removed from the site?

        • nascardriver

          "immediately" means "right away"
          The text doesn't go to the screen right away. It's stored in memory until it stream gets flushed.

          "stream is closed" happens when the application ends. Whatever you print, you can be sure it will appear on screen at the very least when the application ends. You don't need to flush at the end of the program, it happens automatically.

          The edit function appears to be broken, I contacted Alex about it. Thanks for letting me know, I thought it was just me.

        • Satyo Jena

          I used "/n" instead of "\n",
          and it printed 12142 .
          what does that mean?

          • nascardriver

            You probably used '/n' (single quotes, not full quotes). Single quotes are used for individual characters, but /n are 2 characters. If you use single quotes with more than 1 character, the value is implementation-defined.

  • N9

    Hi, I tried the code as suggested here and, from what I can tell, I punched everything in correctly, but when I run it in the command console, my output keeps adding the numbers 12142 to the number I input. I'm using StudioVisualizer and seem to have all the same options selected as the guide here does. Can you help?

    • blackfox

      I am using the same. When I removed the '\n' function, it started working properly for some reason. Oddly enough, once I added the '\n' function after I removed it before, the program continued to function properly.

  • qwerty

    I wrote a program to calculate simple intrest , but in place of the answer its showing some random garbage numbers. Please correct me where i am wrong.
    I used notepad ++ for witting and compiling.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]