Search

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 iostream library

The iostream 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:

std::cout

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:

4

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

This produces the result:

5

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

std::endl

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:

Hi!
My name is Alex.

Tip

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.

Warning

‘\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

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++ iostream 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.

Summary

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
Index
1.4 -- Variable assignment and initialization

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

  • Ahmed Ahmed

    How could I make these cin and cout accept Arabic language(also Arabic symbols) ?
    I'm using visual studio.

  • Marcus

    hi, trying to learn c++ but i am not able to writ to my program ( to enter a number)

  • l1b3rator

    #include <iostream>

    int main()
    {
        /*int x = 4;

        std::cout << "x is equal to: " <<x;

        return 0;
        */

        int x;

        std::cout << "Enter a number: ";
        std::cin >> x;
        std::cout << "You entered: " << x;

        return 0;
    }

         This example works just fine, but i've tried entering "4fc" instead of an integer and it displayed the correct integer "4". But if i enter "f4c" it displays "0", the same happens if i enter "fc".

    So, i guess that cin "reads" the first character from the string that you enter and if it is an integer it stores it in "x", then it "reads" the second character from your string and if it is not an integer then it ignores everything else that follows. If the second character is also an integer it "combines" it with the first integer and stores in "x" the resulted integer, for ex: if you enter "24f" it will store the value 24 to "x"
    If the first character that you enter is not an integer, than it stores the value 0 to "x"

    If my assumptions are wrong, please correct me.
    Thank you.

  • Hithu

    Why do we need to type "std" before cin and cout

    • "std" refers to the "standard" namespace. Namespaces are environments used to prevent names from getting mixed up. @cin and @cout are declared inside the @std namespace. You access namespace members by using the namespace's name followed by :: and the member's name.

  • Brian

    When I typed in the code of the example program myself, and after I debugged the program, the console would exit after I enter a number. It wouldn't even state "You entered 4" for some reason. Why is the program closing too early?

    • When the program is done, the console closes. If I understood correctly this has been changed in VS so the console now stays open.
      If you don't have VS you can either run your program in your command line or add

      before the return statement in main.

  • spacediver

    Alex, thanks so much for this site. Love the fact that you update it!

    Towards the end of this section, you write:

    << is used with std::cout, and shows the direction that data is moving from the r-value to the console. std::cout << 4 moves the value of 4 to the console

    I can see how "4" in std::cout << 4 is an r-value, but would your statement still hold true in this case?

    int x = 4;
    std::cout << x;

    (in this case, would data be moving from the l-value to the console?)

    Not nitpicking for the sake of being a pain, just want to make sure I've not missed something!

  • Fateh Chadha

    #include<iostream>

    int main()
    {
        int y; //special kind of declaration statement called defination
        y = 5;
        y = 2 + 5;
        y = 2 + 3;
            

            int x;
            x = y;
            x = x;
            x = x + 1;

            std::cout << x; //prints the value of x into memory location
            std::cout << 2 + 5;   /*you can even put a single digit such as 3*/

        
        std::cin.ignore(100, '/n');

    }

    Why when I debug this, do i get 67 as an answer. And it is always the same. Even when i reverse '2 + 5'.... you could even put a single digit but the answer is different.

  • sachin

    Hello nascardriver

    thanks for your reply :)
    new to this site and to c++

    Regards

  • sachin

    adding my query to yu's query

    #include <iostream>
    include string
    int main()
    {
        std::cout << "Enter Your Name" << std::endl;
        int y
        std::cin >> y;
        std::cout << "You Entered " << y << std::endl << y << " is a beautiful name." << std::endl;
        return 0;
    }

    if i want to print my name then what should i have to add?

    • Hi Sachin!

      Please use code tags (See yellow message below the comment box).
      @int can only store integers. You need @std::string.

  • yu

    Hi, much thanks for this tutorial! for some reason my when i declare x as an integer with int x; , and i input using std::cin, afterwards my outputs with std::cout << x all say "o"]

    and the output is
    Enter Your Name
    something
    You Entered 0
    0 is a beautiful name.

    Does this have anything to do with using an online shell?

    edit.... i got it, i realized that int only works with numbers. how stupid of me (T-T)

  • mrwiffler

    Hey Alex and everybody,

    Quick question. Instead of outputting "You entered x"(with a space between entered and x) i'm getting "You enteredx"(no space).

    I've been googling and can't find any answers. What am I doing wrong?

    EDIT: Don't worry, I worked it out. You have to put the spaces you want inside the inverted commas surrounding your text. Der.

  • Alex,

    thank you for this great website and content.
    I am a total n00b at programming but I want to learn to make games and software for my businesses, and with your site I feel like I might be able to get there one day...
    Thank You !

  • Jan Williams

    Help...

    Output from build:
    1>------ Build started: Project: Multiple Lines, Configuration: Debug Win32 ------
    1>Multiple Lines.cpp
    1>stdafx.obj : error LNK2005: _main already defined in Multiple Lines.obj
    1>C:\VSProject2018\Multiple Lines\Debug\Multiple Lines.exe : fatal error LNK1169: one or more multiply defined symbols found
    1>Done building project "Multiple Lines.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • Disable precompiled headers in your project settings and remove

      Make sure you don't have another @main function somewhere in the same project.

    • Alex

      I don't see anything obviously wrong here. Please check that:
      * Multiple Lines.cpp only contains one main() function
      * There are no other .cpp files in the project
      * Make sure you don't have a main() function defined in stdafx.h
      * Try doing a clean rebuild, which will force everything to recompile from scratch

      If all else fails, try recreating the project from scratch.

  • Rama

    July 1, 2018 at 5:30 am · Reply
    Hi, Alex
    I'm a complete newbie. So please forgive if this just a simple mistake.
    I type the example:

    then I press the CTRL + F5 to start without debugging in Visual Studio 2017.

    After that, I edit it with the next example:

    But when I press CTRL+F5 again, it run the first example, not the edited one. Why is that?

    • nascardriver

      Hi Rama!

      Ctrl+F5 only debugs but doesn't compile. I think there's a popup letting you choose if you want to compile first when you debug for the first time in a new project.
      Try building (Ctrl+Shift+B or Ctrl+F7) before debugging.
      I might be wrong, I'm not using VS.

  • Southern

    Hello everyone, can you explain for me what is "#include <stdafx.h>??

    • nascardriver

      Hi Southern!

      See Euro Micelli and Mark Amery's answer over at stackoverflow ( https://stackoverflow.com/questions/4726155/whats-the-use-for-stdafx-h-in-visual-studio#4726838 ).
      Basically, it's meant to speed up compilation. If it's causing you any trouble disable precompiled headers in your project settings. I generally don't recommend using them, because they prevent cross-compilation.

  • Reyansh

    thank you man!!
    for such a page,before checking out your page i was quitting computer science branch but after this i kindaa felt i am loving coding and this made me tell people about this page and help people like me to learn c++ easily
    a great admirer of your page

  • ehsan rezai

    hi, i actually started to work with programs and i had 0 background knowledge like i had no idea how programs even work, but i saw your website and this article and it sounds amazing,so i downloaded the visual studio and started working, well now i think i found the love of my life! now i dont waste my time on playing games and im just working with visual studio! thanks for writing this and providing it for free,well im kind of new but i will try harder, just wanted to say thank you ,and if there is kind of donation or sth i can do to return the favor , i would be glad to do so. <3

  • Micah Cary

    Hello. to whoever maintains this, I really want to thank you for putting your time into it and making it free to use.

  • Nguyen

    Hi Alex,

    In the output of std::cin

    For example (I entered 4):

    Enter a number: 4
    You entered 4

    I am wondering why there are two lines instead of one (
    Enter a number: 4You entered 4)?

    Thanks, Have a great day.

    • nascardriver

      Hi Nguyen!

      When the user presses return a linefeed will be inserted.

      • Nguyen

        Thank you....then what if I'd like to see everything printed on the same line (Enter a number: 4.  You entered: 4)?

        • nascardriver

          As far as I know there is no standard way, because the line feed is inserted by your console/terminal, not by your program. You'd need to use terminal/OS-specific solutions.

          • Alex

            > You'd need to use terminal/OS-specific solutions.

            Or better, a cross-platform library that abstracts these into a common interface, such as the curses I/O library (e.g. https://pdcurses.sourceforge.io/)

  • Arntzen

    Hey, I have written the "input your number code" exactly like you have in the example and I click on the "Local Windows Debugger" button with the green play button/arrow next to it in Visual Studios. The program runs as it should, but when I put in a number and hit enter, the console window closes and in the output window in Visual Studios it shows those "bla bla... Cannot find or open the PDB file.

    Did the program run as it should or what? I hope I am running the program from the right thing (the one you find under "Debug > Start Debugging" or F5) or am I totally lost?

    Thanks in advance :D

    • Alex

      Yes, that is the expected behavior. The debugger probably ran, but it likely didn't stop because you didn't set any breakpoints.

      All of those missing PDB files are probably windows system files that don't have debugging symbols available. You can ignore those notifications.

  • Ammaar

    Hi Alex,
    Thanks for these tutorials. Using what I learned I made my own calculator. It can add, subtract, multiply, and divide. Thanks a lot Alex.

  • brunda

    why we have to use "stdafx.h"

  • PatrickC808

    Hi Alex,

    Very helpful tutorials and very good at easing me into the world of c++. i have been having an issue that i hope you can solve, i have the 'hello world' program written up, it says the build succeeded, but the console command box never shows up saying hello. I've tried a lot of fixes, its not that the box appears and quickly closes after running the program, it never runs the program. I decided to continue reading and gave the std::cin tutorial a try. Unfortunately, i never get the chance to enter a number for the program to receive, resulting in Visual Studio telling me it succeeded, when nothing has happened. I'm a noob so i apologize if this is an easy fix and beneath you. please help ?

    • Alex

      It may be obvious, but are you actually running your program after compiling it?

      If so, then try temporarily disabling your virus scanner or malware detector, and see if that fixes it. Sometimes these interfere with things they shouldn't.

  • Cosmin

    Hello! I have a question: what is the default type cout prints? For example:

    I wonder if the type of the argument cout takes affects the value printed. For example, in the first case, I printed an int, but the value was too high and therefore, it overflowed. In the second case, it is the same value, but LL converted it to a long long, and cout printed correctly.

    • nascardriver

      Hi Cosmin!

      This has nothing to do with std::cout. The compiler will decide what type the number is before it gets passed to std::cout. std::cout only prints whatever is passed to it.
      Your compiler decided to make 1 an int and the 9th a long long. You explicitly stated that the other 1 is a long long so there's nothing for the compiler to do about it.

      The bitshift operator doesn't affect the type.

      Here's an example of what gcc 5.4.1 did

      Output

      As you see, here the 9th are a long, not a long long.

  • sonia

    hey!this tutorial is really of great help to me as it covered all the basics in the easiest way.

  • shubham

    hye alex this code
    //#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; // no need to initialize x since we're going to overwrite that value on the very next line
        std::cin >> x; // read number from console and store it in x
        std::cout << "You entered " << x << std::endl;
        return 0;
    }
    is showing submission limit reached in codechef ide.

  • Daniel

    What is the advantage to using std::cout instead of placing 'using namespace std;' after the include statements and just using 'cout' 'cin' 'endl' etc...?

    • dolx

      I've heard that using the standard namespace (using namespace std) is bad practice because it can cause syntax related errors. I guess you could google that though.

      • Daniel

        Thanks for the reply. I looked it up and found this answer on stackoverflow: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

    • Alex

      There's less chance for naming collisions. I talk a lot more about using statements (and why to avoid them) in chapter 4.

  • Anonymous

    Hey Alex, novice programmer here, why wouldn't you just utilize \n within the string to gain begin a new line? As opposed to std::endl?

    Also, great tutorial.

    • MikeL

      On different operating systems, a new line might consist of something other than '\n'. By using the library definition for the OS you are building on, you are guaranteed that it will be correct. In addition, using appropriately named variables makes programs more readable. ;-)

    • nascardriver

      std::endl flushes the output buffer (The text will be displayed immediately) whereas '\n' does not and the text might take a moment until it's printed to the console.
      '\n' is useful when you want to print multiple lines at the same time, you'll have '\n' in every but the last line and only the last line will use std::endl, because std::endl is slower than '\n'.

  • Abdo

    Hello Alex. I've been playing around with what I know from this tutorial so far, and surprisingly there's never ending ways to practice what I know despite that I'm still this early in the tutorial. One thing i noticed about std::cin is that it ignores everything after a space. so if in the console the user inputs:

    How was your day? :awesome and cool

    And then i print the variable in which I stored the input in, i get only:

    awesome

    and it ignores the rest of the input. Do you know if it's possible to get around this somehow while still using std::cin. And if not then is there something else that can replace std::cin that doesn't ignore spaces?

Leave a Comment

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