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

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

  • Jose

    Hi, when I enter a letter ("h" for example), it prints "You introduced... 0".
    Shouldn´t it print the value of "y" given that this is what I used to initialize "x"?

    I checked and if I print the value of "x" before asking for user input, it prints correctly the value of "y" used for initializing "x".

    Visual Studio 2019

  • Marie Bethell

    So I got this - warning: extended initializer lists only available with -std=c++11 or -std=gnu++11| - while compiling the example code for std::cin. I get that it's just a warning and it compiled fine but I think somewhere else you said that warnings should be treated as errors? Anyway, I just wanted to know it there's something I should do about it. Thanks!

    • Make sure you followed lesson 0.10 and 0.11. The settings are project-specific, so you'll have to apply them every time you create a new project. You might be able to create 1 project and apply the settings, then save that project as a template.
      These tutorials use C++11, which you didn't enable.

      • Marie Bethell

        Oh, okay. I didn't know that they were project specific. Reapplying the instructions for warnings did the job (now I don't get that warning anymore) and I saved that project as a template. Thanks a lot!

  • Robert

    //What about
    using namespace std;

  • Renae

    Hi Alex/ Nascar driver

              I understand this - std::cin >> x moves the value the user entered from the keyboard into x
    but I don't understand this - std::cout << 4 moves the value of 4 to the console

    Does it mean the "number" 4 moves the value of 4 to the console
    (so whenever I type in the "number 4", it moves the value of 4 to the console.


    Is it the "variable" 4 moves the value of 4 to the console
    (so whenever I type in the "variable 4", it moves the value of 4 to the console.

    Okay, I understand that std::cin is used to send data to the console to print out both text and numbers.
    But what I'm finding difficult to understand is:
    "(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"

    • If you give it a value, it prints the value. If you give it a variable, it prints the value of the variable.

      > I understand that std::cin is used to send data to the console
      *`std::cout`. `std::cin` reads data.

  • Destiny

    In the above... it is written

    (if std::cout represents the console, the output data is moving from the variable to the console)
    (if std::cin represents the keyboard, the input data is moving from the keyboard to the variable)  

    Does this mean std::cout ALWAYS represents the console / and std::cin ALWAYS represents the keyboard?

  • fadhel

    in the quiz section, question #1.

    Why do we get a zero when we give h or any alphabet to x and not the ascii value.
    similarly, why do we get zero when we enter a string like "hello" into x.

  • Jonas

    Found an error in the final best practice block (asterisks mark the missing word):

    'In line with our previous recommendation that variables should always *be* initialized, best practice is to initialize the variable first.'

  • Hi
    I have a doubt about the difference between endl and '\n'.

    I tried the following code:

    The output is 1 2 3 4 5 but the program outputs all integers at once when the program ends. This is understood as the buffer is not flushed until the program ends.

    When I tried this:

    The output is
    and the program outputs every integer one by one. This is also clear as endl flushes the buffer every time.

    But when I replace std::endl by '\n' as in the following code:

    I get the same output as when I used endl i.e. the program outputs the integers one by one with new line. According to the instructions given here, '\n' shouldn't flush the buffer and the output should appear all at once when the program ends.

    Kindly help me with this doubt.

    I am using Codeblocks IDE on Ubuntu 16.04.

  • Rylee

    I understand that std::cout is mainly used to print words and numbers to the console. But I'm finding it difficult to understand what std::cin is for? What is its purpose?
    Does it just mean, using this ">>" will allow you to write "enter a number" and "you entered" on a program?
    ORRRRRRR? I'm so confused

    • Your console can either listen or write, not both at the same time.

      Read input from the console and store it in `i`. When the user presses enter, the console stops listening and your program continues.

  • Chayim Eliazer

    What does "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" mean??
    What does it mean "it makes sure it shows up" every code shows up immediately when compiling, and this is what it is supposed to be.

    • > every code shows up immediately when compiling
      Compilation is the process of converting source code into a binary. No text shows up in this step.

      @std::cout may or may not print the text you give it to the screen. It stores the text in a buffer and prints it at some point in the future. Unless you flush it, then it's printed immediately. Usually it's printed so fast that you don't notice a difference when you flush manually or let it happen on it's own. You sometimes need to flush when you're printing from inside a long-running loop.

      • Chayim Eliazer

        I don't understand
        Where is it printed if it's not compiled and executed? because we are not talking about compiled source and executed .exe

        • > we are not talking about compiled source and executed .exe
          We are. Code that runs at compile-time is covered in later lessons.

          It gets buffered when a call to @std::cout.operator<< is encountered at run-time and printed when the stream is flushed (eg. by calling @std::cout.operator<< with @std::endl or @std::flush), or at an implementation-defined time.

  • Chayim Eliazer

    IN this page you say that "cout" stands for “character output”, and page chapter 1.1 you said that std::cout (which stands for “console output”)

  • Lisa

    how come this example worked for me (one that i found in the comments)

    #include <iostream>  
    int main()
        std::cout << "Enter a number:" << std::endl;
        int x = 0;
        std::cin >> x;
        std::cout << "You Entered" << x << std::endl;
        return 0;

    yet this example below didn't work for me (the same EXACT example yous put up)

    #include <iostream> // for std::cout

    int main()
        int x{ 5 };
        std::cout << "x is equal to: " << x << '\n'; // Using '\n' standalone
        std::cout << "And that's all, folks!\n"; // Using '\n' embedded into a double-quoted piece of text (note: no single quotes when used this way)
        return 0;

  • Mabel

    Hi, if I'm trying to place 2 things that you guys taught us: this ("std::cin) and the hello world program. How would I place everything together so that I don't get an error.

    #include <iostream>

    int main()
        std::cout << "Hello, world!";
        return 0;

    { (this is line 9 - Ps. I didn't write this little text in the program)

        std::cout << "Enter a number:" << std::endl;
        int x = 0;
        std::cin >> x;
        std::cout << "You Entered" << x << std::endl;

        return 0;

    The hello world page works perfectly on its own, as well as the std::cout. But together it has an error that pops up. Errors are
    - expected a declaration and { missing function header (old style formal list?) both in line 9

  • cronk

    "The iostream library contains a few predefined variables for us to use. One of the most useful is std::cout..."
    I'm confused, how is cout a variable? A variable is a value in a region of memory, then how come cout, which outputs to the screen, is a variable? Shouldn't it be called a function or something?

  • Varun Thakur

    hey.when I complile the std::cin program, it keeps on showing that `NO OPERATOR ">>" MATCHES THESE OPERANDS.`what should I do?

  • alfonso

    I didn't initialize x in any way but still the console displays 0 in respective cases. So, how "x stays INITIALIZED to 0" can be an precise answer for the problem?

    • uninitialized variables have an undefined value.
      It might be 0 every time for you, it might be different with another compiler.

      • Doa

        Your compiler is being nice to you by putting 0 to uninitialized values. If you export your program into an .exe file and run it that way, you will see what is called garbage value. (very large random integer)

  • Prateek

    I have doubt in above Quiz Question #1, option no.(b)
    If x is brace initialized, why does it drop fractional part?
    if input is like 3.2 and then it gives out just 3.It should have shown a compilation error instead as you taught during brace/uniform Inialization.

    Please do reply.
    Thank you.

    • Alex

      The compile error for narrowing conversions with uniform initialization only happens at compile time. In this sample program, x is zero initialized, so there's no narrowing conversion there.

      The dropping of the fraction in this case happens at runtime when the input is extracted into x.

  • Prateek

    When you were discussing brace initialization you said that if you put a number like 4.5,it will show an error message(since variable is not copy or direct initialized).
    In quiz you said that if you enter 3.2 from keyboard,it will drop fractional part.
    I didn't get this?
    Kindly explain why will it drop fractional part if the variable is brace initialized?

    • Brace initialization disallows initialization from types where a narrowing conversion would be required (eg. double to int).
      In the quiz, @x is initialized to 0, which is fine.

      ints cannot store floating point numbers. @std::cin::operator>> extracts everything up to the decimal point and stops extraction there, because anything with a decimal point cannot be stored in an int.
      If you enter "3.2", the "3" will be extracted and ".2" remains in the input (and could be extracted later, but not into an int).

      • Prateek

        I read your explanation.I read what Alex mentioned above.
        Went through the explanation of uniform Initialization.
        But I didn't get anything...
        I then read these all again (for like 5 times) and then again word by word and Mission Accomplished !
        I got it !!
        Thank you for considering my silly doubt .

  • yeko

    thanks for the lesson again and again very funny and good :)

  • Bruno

    It goes to 2147483647. Won't go to 2147483648. Cool :D. Well, i find it cool.

  • Haroon Khalid

    how to directly output an input from the keyboard. (means without using variable)

  • Dots

    Not sure if someone commented already:

    At the quiz time part, you can also try inputting something like "7 tablespoons" and look at the output. Seems interesting (to me at least)!

  • LDawg

    int main()
        int num{};
        std::cout << "Enter a number between 0 and 10!";
        std::cin >> num;
        std::cout << "You entered " << num << '/n';
        return 0;


    Enter a number between 0 and 10!
    // I press 2 then nothing happens. I press enter
    You entered 212142

    Why 212142 instead of 2? I'm confused...

    • LDawg

      I'm going to correct my mistake incase someone else makes it. at the end of my cout I had a forward slash n '/n' instead of a backslash n '\n'. Not the same thing. Valuable lesson.

    • yeko

      oh sorry this issue you know okey

  • Rohan

    To compile you code in Mac

  • I tried this on mac (which uses clang in stead of gcc even if you call for gcc or g++, maybe that's what causes this???)

    I used multi code blocks to make sure the c++ code line numbers would remain correct all the time. I just copied the code above, no alterations. Now if I replace "int x{ };" with "int x = 0;" the code compiles without errors. Since I've already been coding for ages, maybe I went too quickly though some compiler config chapters and missed something, or is something else the matter?

    ( Hey, C and C++ are pretty new for me. Up until now I used Lua, BlitzMax, Pascal, Go and C#, hahaha! )

    (NOTE! And for some reason, the code blocks in my comment don't work anymore after editing this message. Is that a bug? nvm-Renewing the page "fixed" that issue).

    • Supplement, now I've been playing around with this, and it appears that the c++ compiler on mac simply deems {} for variable definition unacceptable.

      The code above compiled and works

      And when I compile this I get this error:

      I'm personally not very fond of using ( and ) for a variable value definition, as I might easily confuse them for functions, but using { and } and having to pray I'm using a compiler that accepts them is also not a very charming solution :(

      • Alex

        It sounds like your compiler may not be C++11-compatible, or if it is, that option might be turned off.

        • I see... I was already looking in version issues so I tried "g++ --version" and I got this:

          EDIT: I've found this on stackoverflow and there I saw the advice to use this to compile on Mac:

          I tried this and that appears to be working.... Perhaps this is good to know for other Mac users using this tutorial

          • Hi Jeroen!

            When compiling with g++ or clang++ (Probably more), one should specify the standard version. This should be addressed in lesson 0.7 @Alex.
            C++11 is already 8 years old, clang 9 has partial support for C++20, use that.

            All the other options enable more warnings and disable compiler extensions as recommended in lesson 0.10 and 0.11.
            Compiling manually will become tedious when you have lots of files. Once you get there I recommend you looking into CMake.

            • Ah, thank you for that information.
              I know that C and C++ have a lot of typing work for compiling when it handles big complex projects, so I have been looking at MAKE already and I will also investigate CMAKE... And I guess I should make note of that way you called clang++ there ;)

  • delFlaco

    The work "use" is missing in the "The iostream library" part at the top:
    We’ll ... the function...
    "at the top any code" - missing the word "of"?

  • Eccentric Song

    Hi Alex,
    I've just started my adventure with C++ and wanted to shout out just how much I appreciate your work on this site. The first three chapters updating yesterday was a surprise, to be sure, but a welcome one - and I immidiately went on to revieving the updated material. That said (and finally moving on to the true purpose of this rant), I believe I've spotted a typo:
    "We’ll the functionality in this library to get input from the keyboard and output data to the console."
    To my understading the beginning should be:
    "We'll be using the functionality..." or something along those lines.

    Thank you again for this great tutorial, keep up the great work!

  • Alex said before that @std::endl is easier to understand for a beginner than '\n'.
    @std::endl immediately prints the text to the screen whereas '\n' could stay in memory for a little while before it gets printed. @std::endl is slower.

  • vito

    Is std::cout considered an l-value here? And what about std::cin

  • Stoil

    Hi, i tried putting this code in Visual Studio but it keeps giving me an error ("fatal error LNK1168: cannot open C:\Users\ASRock\source\repos\Project3\Debug\Project3.exe for writing")
    It still works if i skip this step, though

Leave a Comment

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