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

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

  • progracryptro

    this is just some of the info i got so far

  • progracryptro

    #include <iostream>
    using namespace std;
    int main ()

        cout << " Welcome to phase two of the if statemants " << '\n';
        cout << " Input your lucky no-" ;

        int F {};
        cin  >> F;
        if (F <= 50)
            cout << "Hi script kiddie";
            if (F != 50 )
                cout << "Sorry press enter to abort";
                cout << "Error don't think you know what you're doing";


       return 0;

  • Diogo Albuquerque

    hope you like it, i'm following the tutorial, this was made by me with the information that I gather from this website and some other books.
    I'm putting this code here to see if I can get some inside from experience programmers on where can I imporve.
    Thanks you all!

  • Ronit

    In the question#1, I initialized the int variable x with value 4 instead of 0. When I tried putting string value in input, on prompt, it printed out 0. Shouldn't it print 4?

    • nascardriver

      `std::cin` sets the variable to 0 is extraction fails.

      • Ronit

        But in his book Stroutstrup gives this example,

        Now the input 22 Carlos will output
        Hello, 22 (age –1) "
        Why didn't it print out "Hello, 22 (age 0)"

        • nascardriver

          The behavior changed 9 years ago in C++11 to override `age` to 0 if extraction fails. If you're reading books, you have to be aware that they might not be up to date. If you're reading an old book about best practices, I suggest reading it after you know what the functions do in modern C++ or you'll have to read through the language changes that were made since the release of the book to make sure it's still relevant.
          For a more modern best practice guide (Also authored by Bjarne Stroustrup), see the core guidelines. These require you to have knowledge of the language already. The explanations aren't as detailed as the ones in your book.

        • alex

          // fixed your script

          #include <iostream>

          int main() {
            std::cout << "Please enter your first name and age\n";
            std::string first_name = "???";
            int age{ -1 };
            std::cin >> first_name >> age;
            std::cout << "Hi, " << first_name << " ( Age " << age << " )\n";

  • shawn

    When I put in a large number I get:

    but when I do a large negative number I get:

    Why aren't these the same? Does the first one include 0?

  • Chetna

    We are using braces. So why isn't there any error when we are giving input like "4.5" when datatype of our variable must not allow that. As we are using braces, we must encounter error rather than just droppage of fractional part?

    • nascardriver

      If you provide a literal, such as 4.5, a conversion is allowed if it is lossless.

      • Chetna

        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).

        Hide Solution

        The fractional component is dropped.

        int x{}; // define variable x to hold user input
        (Why fractional component will drop in this case when we have used braces and datatype is int. Must it not
          show error?)

        • nascardriver

          The previous value or type of initialization is irrelevant in this example. Initialization happens during definition of the variable, it has no effect after that.
          `std::cin` extracts as much as it can. When a fractional number is input and an `int` is expected, `std::cin` doesn't know what to do with the dot, so so it stops extraction. For example, if you enter 3.7, `std::cin` will extract the '3', then it sees the '.', but doesn't know what to do with it, so it stops.

          • Pranit

            But in section 1.4, in the uniform braces section, you told us if we input value of other data type(like float) to int data type variable,it would follow with an error(which is an added benefit).But this is not the case when we are implementing here.Rather, it's just dropping out fractional part like any other initialization types.

            • 3LI M 3alim

              In section 1.4 (The Uniform braces section), I think the auther is not talking about different types of variables(int,float, ...), instead, it is about different types of initialization(single number , list of numbers,..).

            • korean

              I think we should know the difference between initialization and assignment. When brace 'initialization', it must show an error. But in b), not the case 'initialization' but 'assignment', it just dropped fractional part.

  • Jay

    In Q1 on Quiz time, line 6 where the zero initialization is done...

    int x{}; using this on line 6, produces an error: expected ';' at the end of declaration

    So instead, I removed the curly braces and there was no compiler error --> int x;  

    I use Visual Code Studio on Mac OS Mojave. (Compiled using g++ and ran the executable).

    Can you please explain why the original program produced an error and the modified version doesn't?

    • DashwoodIce9

      Are you sure you placed a semicolon after

      The error message is pretty clear. You are missing a ';' after declaration.

    • nascardriver

      You're using an old compiler or didn't configure yours correctly. You need at least C++11 for list initialization. See lesson 0.12.

  • Josh P

    I noticed this while doing Hello World as well but when I do the 'start without debugging' everything comes up great to start.  Then it asks me to enter a number, which I do.  It gives the correct response but then after that it says

    C:\Users\****\source\repos\Enter a number\Debug\Enter a number.exe (process 12264) exited with code 0.

    Should that last line appear whenever I'm doing the 'start without debugging'?  Is there a way to get rid of it?

    • DashwoodIce9

      "(process xxxxx) exited with code 0" means that your program executed and terminated successfully. The code "0" is coming from the "return 0" line in your code. It is the last line executed before program termination. This is perfectly normal. You should be worried if you see something else instead of the return code specified in main.

      If you are curious, try changing the return value from 0 to some other integer, and see the output after program termination. Also, see what value is generated when you do not allow the program to terminate normally, for example - instead of providing an input for "x", just close the application forcefully.

  • flushes the output buffer

    What does "flushes the output buffer" mean? And why it should be flushed by std::cout? What would happen if the output buffer wasn't flushed?

    • nascardriver

      Flushing the output buffer means moving the text from memory into the console. If the buffer doesn't get flushed, you don't see anything, but flushing the buffer is expensive, so it should only be done when necessary.

  • Naresh

    This is not working as I expect it to. The execution is such that line 12 (getline(cin, name) ;) is just skipped altogether. However when I run the part of code excluding the lines 5 to 8, the code works as expected of it.

  • sam

    Thanks for your wonderful site!
    I have a question:
    You said:
    The iostream library contains a few predefined variables for us to use. One of the most useful is std::cout ....

    I think cout is not a variable it is an object of a class. They should be called objects not variables, what do you think?

  • Abhishek

    I have some confusion regarding the statement iostream library is part of C++ standard library.Isn't iostream a class and the C++ standard library which if I am not wrong is libstdc++ is colllection of all obj files compiled from source code of classes like iostream ? In simple words, is iostream a class or library ? If it is a library then does c++ standard library have lib files instead of obj files ?

    • nascardriver

      "library" in "standard library", and also in general, doesn't always mean compiled code or object files. Although "library" can refer to the object file, "library" generally means a collection of code, no matter how it's shipped. Some entities are a direct part of the standard library, others are part of sub-libraries of the standard library. This includes the input/output library, of which the iostream class is a part.

      I removed "iostream library" from the lesson. It's a class (Though the lesson also talks about the iostream header), the library is the input/output library.

  • Jim Guth

    Here is an example it all the code in this lesson.  It builds/runs fine in code blocks. Note the different ways the code is used in various lines.  Have fun while your coding!

    #include <iostream>

    int main()

        std::cout << "Hi!" <<std::endl ;
        std::cout << "My name is Jim."  << "\n";
        // note the use of backslash
        //(all special characters in C++ use a \(backslash)
        std::cout << "Hello world!\n";
        std::cout << 4 <<'\n';
        // note the use of single quoted for \n.
        int x{ 5 };
        // define integer variable x, initialized with value 5.
        std::cout << "x is equal to " << x << '\n';

        std::cout << "Please enter a value for y ";
        // ask user for a value for y.
        int y{ }; // define a new variable y
        std::cin >> y;
        std::cout << "You entered a new value for y = " << y <<'\n';

       return 0;

  • Parsa

    Does std::cin read until a newline was removed, or until EOF? EOF doesn't really make sense to me because the stream would need to be empty for it to ask for input.

  • Karbon62

    I had the same problem.

    I basically commented out all the other files using '//'. I then ran the file again and it worked.

    Im using Xcode but it should apply the same for all editors, since all your files are nestled under run 'project'.

  • José

    I need help. I was reading this entry, and since I couldn't fully grasp it. I wanted to practice with this programs, so I copy-pasted them on VS19, but when I tried to compile it, I got the error LNK1168:

    1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------
    1>LINK : fatal error LNK1168: cannot open C:\Users\josee\source\repos\HelloWorld\Debug\HelloWorld.exe for writing
    1>Done building project "HelloWorld.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    I searched on google, forums, and I found nothing helpful, now I'm completely lost and don't know what to do. Any kind of help would be appreciated.

    And thanks for this tutorials, they are trully useful

    • Lucas Stern

      Jose, this error happens when the linker cannot create, open or edit a file, in your case `HelloWorld.exe`.
      Probably you are overwriting an already created file, but that file is being used (maybe com a cmd process that you forgot to close?), or your user don't have the permission to write on your current folder (unlikely, since you are inside your own folder).
      Check if you don't have any helloworld.exe running or try to open VS19 as admin.

      • José

        I forgot to give my thanks before.
        I don't exactly know if it was this, or what Alex told me, but, it worked, so thanks, both.

    • Alex

      Try disabling your virus scanner temporarily and see if it resolves the issue.

    • Gio

      I was having the same problem, but after I started a new project the program worked.

  • Robert555

    In another tutorial I started there was a discussion about using the iostream or stdio.h library. I think the syntax of stdio.h is much simpler, clearer and more powerful than iostream. printf is much easier than std :: cout <<. If I may, I will continue to use stdio.h ...

    • nascardriver

      `std::printf` isn't type aware and not extendable. It's easy to invoke undefined behavior and it's ugly to work with once you get to custom types.
      If you can't get used to the stream syntax, I recommend using a type-safe logging library with format syntax.

  • Hi, so far I've understood most of what's been taught,  however I'm on lesson 1.5 and the objective is -

    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

    My issue is that any time I'm compiling the programmes  im getting ' build: succeeded and no errors which is good however with this objective I'm supposed to have an interaction of the system asking me to enter a number and press enter which I'm not getting any thing asking me that ?. What have I missed or done wrong to not get it asking me this ? It can't be the code as I've also copied and pasted the code exactly to see if that would give me the correct outcome and null out my typos etc

  • Vitaliy Sh.

    Hi Sires!
    (<<), (>>)
    ** <code>?

    "... (and press enter), ..."
    "... will need to press the enter key ..."
    "... without the user having to press enter."
    ** Enter (capitalization)?

    "In line with our previous recommendation that variables should always be initialized, ..."
    ** Anchor to 1.4's "Initialize your variables"?

    "... we’d recommend the pdcurses library."
    ** New address:
    ** PDCurses (capitalization)?

    <code>"std::cout << 4 moves the value ..."</code>
    <code>"std::cin >> x moves the value ..."</code>
    ** ``<code>...</code> moves the value ...`` ?

  • Omran

    i made this program , can someone judge me please or rate my code ??? ,

    here it is :  

    #include <cmath>
    using namespace std;

    int main() {

        int x;
        int y;

        std::cin >> x;
        std::cin >> y;
        int sum = x + y;
        if (sum == -x+y or sum == -x-y or sum == x-y ) {
    std::cout << "please enter non negative values\n";
        else {

    std::cout << x <<"+" << y<< "=" <<sum <<endl << "hello world\n";
        return 0;

    • Vitaliy Shatrov

      Use the code tag code ... /code (in []).

      PS: x=-2 y=-4 also prints hello world... if(){} isn't works...

  • How do you create an account on this website?

    • nascardriver

      You can't create an account. You can change your avatar on, it will be linked to learncpp via your email address.

      • omran

        January 3, 2020 at 11:59 pm · Reply
        i made this program , can someone judge me please or rate my code ??? ,

        here it is :  

        #include <cmath>
        using namespace std;

        int main() {

            int x;
            int y;

            std::cin >> x;
            std::cin >> y;
            int sum = x + y;
            if (sum == -x+y or sum == -x-y or sum == x-y ) {
        std::cout << "please enter non negative values\n";
            else {

        std::cout << x <<"+" << y<< "=" <<sum <<endl << "hello world\n";
            return 0;

        • nascardriver

          - Please use code tags when posting code (Yellow message below the reply box).
          - Don't use `using namespace` at file-scope.
          - Initialize variables with breace initialization.
          - Don't use `std::endl` unless you have to. Use '\n' instead.

  • bill

    what does the "int" before main()mean ?

  • Helpme

    Can anyone help me I always get this error in codeblocks when I put the program

    Error: no match for 'operator>>' (operand types are 'std::istream {aka std:: basic_istream<char>}' and 'int() ' )

    • Could be a wrong compiler configuration. Try this instead

      If it works, you didn't set up your project correctly. Make sure you enabled the highest standard (-std=c++17).

    • Kyle

      I had this same problem, on line 6 instead of: int x(0), use: int x{}

  • troxodev

    Hi! anyone know why when we put in the program:

    a big number like 3000000000 get a random number?

  • Mike

    I'm a little confused regarding the solution to A under the Quiz section.

    The solution says "x stays initialized to 0". That infers that because it was originally initiated to a zero-value, that it will "stay' a zero-value if/when a non-numeric value is entered. Yet, I set the value to 5 and tested it again. The result was the same as before: 0. So, it didn't 'stay' initialized to 5, it just defaults to 0.

  • Mike

    While practicing with variables, I used two variables: x=5, y=2.

    For the print statement, I used single quotes to separate the two values with the & symbol, like so:

    std::cout << "The two numbers are " << x << '&' << y << '\n';

    I quickly realized I needed two additional spaces: one before and one after the & symbol, though I forgot to replace the single quotes with double, and thus got a strange result (521069122).

    After some further testing, I see x is the first number and y is the last. The numbers between them seem to be somewhat random.

    I'm curious if anyone knows how this is interpreted?

    • If there's more than one character in single quotation marks, it's no longer a `char` but an `int`. The value is implementation-defined.

      • EyeMayBeIncorrect

        Leaving out the 5 and 2, which are x and y, 2106912 to hex is 0x202620. 0x20 is ASCII for space, 0x26 is ASCII for &

        So, in this implementation, the ' & ' expression got converted to a string concatenation of ASCII codes for space, &, and space, which got treated like an int.

  • Maverick

    Codeblocks uses the statement "using namespace std;" everytime I create a new project. How do I disable this instead of deleting it every time manually?

  • Fernando

    Hey, I checked the next lesson but it doesn't talk about "flush". I have read this

    But I still don't think I quite understand the need for flushing exactly. I understand that it just says "hey, empty the buffer right now and write the content to the output immediately". But I don't understand WHY we need that.

    • Sometimes the automatic flushing doesn't work as you'd like it to. You might encounter this when you write long-running loops and whatever you printed doesn't appear on screen until the end of the loop. In such cases, it's better to flush manually.

  • Omar

    My question might be a little weird but i'll shoot: It was stated earlier that int x{9.3} will draw an error because 9.3 does not fit into our integer container, but when we declare variable 'int y{}' and use 'std::cin >> y;' we do not get an error. Is this because cin does an implicit conversion from decimal to integer?

Leave a Comment

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