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

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

  • Khan Md Sazzad Hossain Khan

    // ConsoleApplication1.cpp : Defines the entry point for the console application.

    #include "stdafx.h"

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

        return 0;

    what is the problem,

    why it shows this error
    Severity    Code    Description    Project    File    Line    Suppression State
    Error    C2143    syntax error: missing ';' before 'std::endl'    ConsoleApplication1    d:\program practice\consoleapplication1\consoleapplication1\consoleapplication1.cpp    11

  • rookiecoder


    I just started using this website to learn how to code a couple days ago. I downloaded the Code Blocks IDE to my Mac. I have gone through all of the tutorials up until this point, and my first project was the HelloWorld program. Everything went fine with that. I wanted to create a new project so that I could enter this program that you recommended.

    //#include "stdafx.h" // Uncomment this line if using Visual Studio
    #include <iostream>

    int main()
        std::cout << "Enter a number: "; // ask user for a number
        int x = 0;
        std::cin >> x; // read number from console and store it in x
        std::cout << "You entered " << x << std::endl;
        return 0;

    I encountered two problems:

    1.) I went to New Projects and created a new console application that I titled Experiment. When I opened it in my Workspace and opened the sources under it, there was a file called main.cpp, which contained the HelloWorld program. I'm confused about how that got there, when my Experiment project is a completely separate project from the HelloWorld project.

    2.) I deleted the HelloWorld program from the main.cpp file in my Experiment project. Then I pasted the above program from this tutorial. I built it and no problems popped up in my build log. I am in debug mode. When I clicked play, my terminal opened, but the program did not run as it should have. Nothing was printed to the console. The return value was 127. I clicked undo a bunch of times so the HelloWorld program was back in the main.cpp file under Experiments. Then I clicked run and build. The program ran and said Help World! Then I deleted the HelloWorld program and pasted the above program from this tutorial again and clicked build and run. Hello World! showed up on my console. What's going on?

    Thanks for your help and awesome tutorials. Sorry for the long message and perhaps dumb questions. I'm definitely a beginer.

    • Alex

      I think Code::Blocks creates a simple "Hello world" program by default when you create a new project.

      I'm not sure what's going on with #2. I'd restart the app, create a new project, then try modifying the hello world program to make sure it's running the program you think it is (e.g. make it write "Hello, moon!"). Once you've established that it is, then you can try pasting in the sample programs.

      • tobson

        I'm having the same problem with HelloMoon!
        There are some Program dependencies in Code::Blocks that I can't seem to get around. Seems the program thinks I want the projects descending from one master project. It's a bit frustrating...

        For example I called the other project "EnterX" and it clearly is a new program, but in the Build Log of "EnterX" Code::Blocks stated:"Release in HelloMoon". I don't get it.

        • Alex

          Make sure you're only creating each project individually (don't try to put multiple projects in a master project). I'm not sure what else to suggest.

  • Vishal

    Hello, Alex. Thanks for the great tutorials.

    After this tutorial, I've been reading Accelerated C++, by Andrew Koenig and Barbara E. Moo, and I came across this question in it.

    Would this work as expected?
    Why or why not?

    I've been intrigued by this for a while. At first, I expected a few compiler errors, but the program compiled and ran perfectly.
    C++ pretty much ignores the whitespace character (

    is treated the same as

    Does the compiler also ignore the newline character?

    the same as

    • Alex

      Yes, expressions and statements can be broken up across multiple lines. That's why statements must end with a semicolon -- it tells C++ where the actual end of the statement is.

  • Tim Munro

    I am having a very tough time making any of these short programs to work.  I copy and paste into my VS2010, and they will not build.  Unsuccessful each time.  Can't run the program if you cannot build it. Example;
    //#include "stdafx.h" // Uncomment this line if using Visual Studio
    #include <iostream>

    int main()
        std::cout << "Enter a number: "; // ask user for a number
        int x = 0;
        std::cin >> x; // read number from console and store it in x
        std::cout << "You entered " << x << std::endl;
        return 0;

    Error messages; 1>------ Build started: Project: std_cin, Configuration: Debug Win32 ------
    1>Build started 3/21/2016 3:06:38 PM.
    1>  Touching "Debug\std_cin.unsuccessfulbuild".
    1>  All outputs are up-to-date.
    1>  std_cin.cpp
    1>c:\users\u081578\documents\visual studio 2010\projects\std_cin\std_cin\std_cin.cpp(2): warning C4627: '#include <iostream>': skipped when looking for precompiled header use
    1>          Add directive to 'StdAfx.h' or rebuild precompiled header
    1>c:\users\u081578\documents\visual studio 2010\projects\std_cin\std_cin\std_cin.cpp(15): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?
    1>Build FAILED.
    1>Time Elapsed 00:00:04.48
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  • Brandon

    I'm having a problem using Visual Studio 2015. For some reason when I press enter after inputting a number, 'You have entered' appears for a second and then the program is closed. I've looked at the common problems page and have tried, 'return 0;', std::cin.ignore(32767, 'n'); and std::cin.get(); but it still does not work.

    Here's what it looks like:

    #include "stdafx.h"
    #include <iostream>

    int main()
       std::cout << "Enter a number: ";
       int x = 0;
       std::cin >> x;
       std::cout << "You entered: " << x << std::endl;

       std::cin.ignore(32767, 'n');

    This site is really great by the way, thank you!

    • Alex


  • Orialdo

    When I put in this code, I only get the first line printed.  I don't receive any errors or warnings.
    Please let me know what I am doing wrong.  Thanks

    #include "stdafx.h"
    #include <iostream>

    int main()
        std::cout << "Enter a number: "; // ask user for a number
        int x = 5;
        std::cin >> x; // read number from console and store it in x
        std::cout << "You entered " << x << std::endl;

        return 0;
    PS:  Running Visual Studio 15

  • Jim

    There is a minor error in this lesson. When you introduce std::cin  above the output of the program will be printed on one line not two as shown.  

    <<std::endl can be mover up from line 9 to line 6 to fix this.

    • Alex

      Incorrect. When we use std::cin to extract a value to variable x, the user will have to hit enter to end the extraction. That will cause a line break to occur, separating the output. Try it yourself.

  • Mehdi

    Hi Alex. (Thank you for the toturial)

    I have recent noticed that Compiler does'nt give error if you write either the one or the other one of the following:
    # include "iostream"
    # include <iostream>

    Which one is (more) Correct?

  • Mohammed Asim

    Hi brother, I need to know the way of reading the inputs at once and then doing the required operation and then displaying the output as in this case where a user receives the inputs--all at once and then prints them back(all at once) after the operation. Is there anyway without the arrays?

    Sample Input:

    Sample Output:

    u can look at the problem here
    I am not talking about the specific problem…but in general..
    I know the logic of the above problem but I am stuck with the I/0..plz help.

  • Nyap

    I'm kind of confused, what is the difference between the standard and iostream library or how are they linked?

    • Alex

      The C++ standard library is a code library full of reusable functionality that you can use in your programs. Anything you see that uses prefix std:: is part of the standard library.

      Iostream is a small part of the standard library that provides functionality to do console input and output.

  • ZombieMcgiggles

    Why do I have to say

    when I can just say

    and it will run just fine? Whats the point of assigning x to 0?

    • Alex

      In this case, since the program asks the user for a value for x on the very next line, there's no need to initialize x with a value.

      However, I still often give my variables initial values anyway. That way, if I change the code (e.g. don't ask the user any more) the variable will still have a known value.

      In my opinion, it's better to program defensively than optimize where it isn't really needed.

  • Nick

    Does anybody know why this code is wrong, code blocks says it was expecting a ; before the std but i tried putting a ; after int main() even thoug i know its wrong and it still doesnt work

    • Alex



      You're missing the << operator for that line, and one other line further down.

  • bob williams

    #include <iostream>

    // subtraction caculator
    int main()
      std::cout << "Enter the first number: " << std::endl;
      int y = 0;
      std::cout << "Enter the second number: " << std::endl;
      int x = 0;
      std::cin >> x;
      std::cin >> y;
      std::cout << "Your answer is: " << y - x << std::endl;


    im trying to make a calculator for subtraction to start off and make something but after i get to the second number the program freezes any answers?

    • Alex

      It's not clear to me why you're using cin.get(). Try this:

  • Devin

    okay so, I tried to create a v small preset conversation, but after the first input, I got blasted with all the preset dialogue.

    #include "stdafx.h"
    #include "iostream"

    int main()
        using std::cout;
        int x = 0;
        cout << "Hello, my name is Alex... What is yours?" << std::endl;
        std::cin >> x;
        cout << "That's a nice name.. can you help me...?" << std::endl;
        std::cin >> x;
        cout << "I'm trapped.." << std::endl;
        std::cin >> x;

        cout << "Inside your computer.. Just press the 'x' button in the top right to" << std::endl;
        cout << "release me from this damned prison.. I will be most grateful..." << std::endl;
        return 0;

    • Alex

      Yes. Here's what happening. You've defined x as a variable that holds an integer. Then you're asking the user to enter text into that variable. std::cin >> x can't figure out how to put text into an integer, so it fails (and that causes the rest of the std::cin statement to get skipped).

      We'll talk about how to deal with text in future chapters. It's a little more complicated than dealing with integers.

  • Abhishek

    turns out, the maximum value x can take is 2147483647, which when divided by 1024^3, gives a value pretty near to two. How that matters, i don't know. :P

  • de_sk

    learning c++ is so much fun...thank you so much for your effort Alex!!

    playing around with example...:)

    / calcualtion test2 using namespace.cpp : Defines the entry point for the console application.

    #include "stdafx.h"
    #include <iostream>

    int main()
    using namespace std;
    cout << "Please use for addition of two or three integer variables" << endl;

    cout << "Enter any first integer number " << endl;
    int x = 9; //  value 0 is given even its not necessary because initializing variables is a good habit
    cin >> x;

    cout << "Enter any second integer number " << endl;
    int y = 0;
    cin >> y;

    cout << "Enter any third integer number (optional type 0 if not required)" << endl;
    int z =0;
    cin >> z;

    cout << x << " + " << y << " + " << z << " = " << x + y + z << endl;

    cout << "Have a nice day!! :) " << endl;

        return 0;

  • Shubh

    Hi sir its SHUBH again with another query

    instead i removed the int x = 0;

    also when i dont put int x = 0 and instead type int x the program runs without any bugs

    • Alex

      x is a variable, not a fixed value. You can assign different values to it.

      In the first example, we assign the value of 0 to x, and then when the user enters a value, that overwrites the value currently in x with whatever the user entered. Giving x a value of 0 in this example is somewhat useless since it just gets overwritten anyway.

      The second program shouldn't compile since you've never declared x. You should at least need "int x" between lines 6 and 7.

  • Shubh

    • Alex

      The last std::endl is redundant in the example. It doesn't matter whether you go to the next line or not if the program is going to end.

      However, I personally put the std::endl there anyway, both for consistency, and because it helps avoid errors if new lines are added or reordered.

  • deepu

    Thanks for this awesome tutorial.

  • Nirvar Roy Vaskar

    Thank you,Alex.Your tutorials are full of relevant informations and also well indexed.I'm writing this comment just to thank you.Love and grattitude from Bangladesh :)

  • Hi Alex,
    with a premise that I am approaching C++ as a former (very former - something like 20 yrs ago) user of C, I'd like to ask you this:
    is there a particular reason why you prefer going to the new line with the "<< endl" instead of adding the "\n" at the end of the string?
    On my compiler (Code::Blocks with gcc 4.7.1 for Windows) they both give the same result, but "\n" is definitely faster to write than "<< endl".

    • Alex

      Mainly because at this point we haven't talked about strings, chars, or special symbols. I cover both std::endl and '\n' in future sections, and reasons to use one over the other.

      But upon reflection, maybe it's worth introducing earlier.

  • D3thtr4p

    So far, this is perhaps one of the best tutorials I've ever used to learn something new. I would have never thought that programming is such an intuitive thing. :)

  • Carol

    Great tutorials! Much better than the textbook I have to read!

  • Satish Chougule

    This site is simply AWESOME!! But it will be better if you provide PDF format of the tutorial. So that we can refer the tutorial off-line too!!

  • Chris

    Hi again Alex it's me again. So I've moved on to this lesson and now that it's happened again I'd like to see if we could get to the bottom of it.

    My problem is that my console is auto closing as we discussed previously. This is great because I have questions now which will hopefully lead to me learning.

    I'll break down the code and also what I'm doing to run it.

    So this is the default code you asked me to use in the example on this lesson. When I put in this code (by the way I'm using VSPro2013) and then click the |> Local Windows Debugger, the program pops up, runs exactly how it should and then when I hit enter after typing a number it closes the cmd prompt window immediately after giving the output. This doesn't give me enough time to make sure it works right.

    So I tried this

    Which in turn gave me an error stating that cin was not identified so I had to do this:

    That code fixed my problem but I'd like to get to the bottom of it if we could so I don't have that problem as I shouldn't by default. I'd like to know what your thoughts are.

    Also why is cin unidentified in the first example? I'd really like to know.

    Thanks Alex

    • Alex

      Both cin and cout live inside the std namespace. If you use "cin" without any prefix, the C++ compiler won't assume you mean std::cin. You either have to use std::cin, or use a "using" statement so the compiler knows that cin really means std::cin.

      So I learned something new about Visual Studio today.
      * If you run your program normally ("Start Without Debugging, keyboard shortcut ctrl-F5), Visual Studio will automatically pause at the end of your application.
      * If you run your program with debugging ("Start Debugging", keyboard shortcut F5), Visual Studio will not pause at the end of your application.

      My suggestion is simply to run your programs without debugging, unless you need to debug. If you do need to debug, you can put a breakpoint on the closing brace of main() to ensure it stops.

      (Note: I found a bug in the website that was causing your '\n' to show up as &apos;\n&apos;. I fixed both the bug and your comment)

  • Debbie

    Great tutorial.  Very well done.  I have a question about expressions.  Is the following considered an expression?  It returns a value to the variable:

    cin >> age;

    I've been wondering about this and can't find an answer anywhere. Thanks!

    • Alex

      I believe so. In this case, your operator is operator>>, and your operands are cin and the age variable.

      • _aleph_

        Does this cin create a variable.  Wouldn't you have to define the age variable first?  This is how I have understood your tuts.

        • Alex

          cin doesn't create a variable, so yes, you'd have to define the age variable first, like this:

  • Dave

    Hello Alex! This site is awesome!

  • Xavi Reyes

    Good job with the tutorials! I'm glad to see you keep active since some pages are from 2007.

    I'm from Spain and it's amazing to see I can understand the tutorials perfectly, I don't need to read it twice to comprehend the content.

    I only write to give thanks to you, you are helping me a lot. Keep this wonderful job!

  • I'm currently using Microsoft Visual Stuidos C++ 2010, but whenever I try to run the example scripts I get errors about the location of the file. Also, is there a different type of program I can download such as an interperator that compiles and runs the script automatically? I do not want to find the file and execute it every time I want to test something simple, such as defining different variables. Help would be appreciated.

    • Alex

      Something is messed up with your installation. You shouldn't have to locate the file and execute it every time.

      I'd paste the error into Google and see if you get any hits on how to fix.

      • Sounds like when you initially installed the program you opted for another directory other than the default (usually used when a custom installation is selected).
        I have seen with some programs this results in the type scenario you are describing.
        You might check in your program options and then check the default directories to see where things are actually being saved and loaded from.

Leave a Comment

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