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

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

Related content

We discuss what the std:: prefix actually does in lesson 2.8 -- Naming collisions and an introduction to namespaces.

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 8, 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 10, 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.

Just like it is possible to output more than one bit of text in a single line, it is also possible to input more than one value on a single line:

This produces the output:

Enter two numbers separated by a space: 5 6
You entered 5 and 6

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 (7.16 -- std::cin and handling invalid input).

For advanced readers

The C++ I/O 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.9 -- 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

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

  • I guess this is just a minor suggestion, but when I read this section I had to google what the STD in std::cout stood for. And I think it would be nice if it was there next to the cout definition.

    From what I found it appears to refer to the standard "name space," I'm not familiar with name spaces yet, but I think defining the abbreviation here would still be helpful.

  • Gokunik

    One better way to understand the cin>>x>>y is the below code

  • Shakib

    <<This code is copied from this page>>

    When I input two random integers with space, it works fine. But if I input a fractional number(i.e. 87.4) and then an integer(i.e. 28), it outputs 87 and 0. Why does it ignore 28? 'y' is totally a different variable. Then why it happened??

    • nascardriver

      You'll later learn how to clear the input buffer and reset broken streams.

  • Joseph Garza

    Thank you very much for your kind collaboration with our learning! That was very nice of you.

  • Manuel Calzadillas

    It's always nice to learn a new programming language
    Thanks Alex

  • David

    "When the code gets to line 7, your program will wait for you to enter input"
    Isn't it the line 8?

    "on line 8, the program will print “You entered ”"
    maybe it's line 10?

  • Andreas Krug

    Two small suggestions after first example of #std::cin:

    - When the code gets to line 8, ...  instead of  When the code gets to line 7, ...
    - Finally, on line 10, ...  instead of  Finally, on line 8, ...

  • nuke

  • Tom

    Could you explain why inputting 1.5 and 1 results in 1 and 0? I get the 1.5 turns into 1 because of int, but why is the second input output as 0?

  • Glowerworm

    It's been drilled into me to leave a comment at the top of any code that explains quickly what it does. Is there any standard way to leave the #include <iostream> and #include <other libraries> at the beginning of the code? Do you recommend having the #include statements before or after the top summary comment? Which is more readable with larger-scale code?

    Also, I've recently been using ROOT to run .C files, and so far I've been able to include input/output without including the #include <iostream> in my code. If the code runs and accepts input/output without that library stated, do I still need that line?

    • Alex

      I typically see file-level comments put above the #includes, and function-level comments preceding the functions they're documenting.

      You should always #include all of the capabilities you use. While things may work fine now if you don't, there's no guarantee that won't change in the future if you upgrade your compiler or try to port your program to another system.

  • jerron

    "In the above program, the second std::endl isn’t technically necessary, since the program ends immediately afterward."
    -- It makes differences with/without endl, say, if you run the program immediately twice in a script.
    "Note that when ‘\n’ is used by itself to move the cursor to the next line, the single quotes are needed. "
    -- Either single quotes or double quotes would work.
    "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)"
    -- not sure if we should mention it, given std::cerr more "usually" flushes output

    • nascardriver

      > It makes differences with/without endl, say, if you run the program immediately twice in a script
      Program termination causes all streams to be flushed (through destruction of `std::ios_base::Init`).

      > Either single quotes or double quotes would work
      Double quotes are more expensive, because they introduce a string containing 2 characters (The line feed and a null terminator). We don't want to teach bad practices, but you're correct, a fully quotes \n would have the same apparent effect.

      > not sure if we should mention it, given std::cerr more "usually" flushes output
      We mention this behavior in lesson 3.5 when `std::cerr` is shown. Mentioning `std::cerr` this early is likely to cause confusion. It can wait until everyone is comfortable using `std::cout`.

  • Chayim

    What does:
    it “flushes” the output (makes sure that it shows up on the screen immediately).

    Mean?

    What does it mean that it shows up on the screen immediately? Which screen? When? What?

    • Alex

      Outputting characters to the console can be slow. So rather than write each output request directly to the console, C++ will hold the output in memory. In this case, the output is only sent to the screen when the memory is full, or when an explicit request (called a "flush") is sent to do so.

      The console is typically displayed on a monitor, so the screen is typically going to be the screen on your monitor.

      • Chayim

        But nothing shows on the screen until the entire program is compiled and executed and then everything shows up on the screen at once, nothing shows up on the screen while programming or compiling so what exactly does flush do?

        • Alex

          All of what we are taking about happens at runtime. After a flush, all output that should be displayed is actually displayed. Prior to that point some output may be cached for display but not actually sent to the display yet.

          • Chayim

            Where is it displayed? do you mean in the console of the IDE? if so that what you'd have to answer my question in the first place: "It's displayed in the IDE console"  that's the answer to my question. Luckily I got the answer by myself after struggling to get the answer from you.

            • Alex

              Your IDE will create a console if you run the program from your IDE. However, consoles are actually a feature of your OS (on Windows, you can create one by running "cmd" from the start menu). From the console, you can run executables (compiled programs) without your IDE.

        • bb

          When you compile and link your file and distribute it to the user and the user uses it, that is called the runtime.

          The article talks after the compilation and linking are done. Displaying something on screen, in such simple code, happens so fast that you perceive it as it is happening immediately. Imagine you don't want to print "My name is Alex" but something that is made from many complex calculations that take time. In that case every new result is added to your desired output but nothing will be shown because the memory is not full. You still want to see the results so far and this is where flushing helps.

          At least this is how I understand it so far.

  • James C

    I think you should point out that you can input values into multiple variables with std::cin and >>. like

    . This isn't mentioned until way later, where it's used in intro to standard library algorithms. In my opinion, when you can, you should sprinkle this across lots of examples.

  • Lennon

    int x{};
    why do we use curly braces after variable declaration.
    it is automatically initialising x to be equal to zero or whatever I put inside the braces.
    ? i have never seen something like this in c++,,what is it

  • ej

    Hi. could you please tell me how to run the program for the quiz after compiling it?
    i copied and pasted the code and it was compiled successfully but i dont know how to run the program.

  • Szymon :)

    I don't understand why do I need to use a third party library to get input from the user, without the need to press Enter.
    I've got this code and it works:

  • //i believe i am typing the code the same as directed in this lesson...

    [#include <iostream>

    int main()
    {
        std::cout << "4: ";
        int x{ };
        std::cin >> x;
        std::cout << "you enetered 4" << x << '\n';
        return 0;
    }]

    //but instead of the console printing 4 when x is input it prints 40... why is this. am i misunderstanding something?

  • Al

    Hi Alex/Nascardriver -

    I really appreciate you guys taking the time making these tutorials. I'm new to programming and I'm using Microsoft Visual C++ 6.0 (couldn't use newer version as work is requiring for us to use 6.0) and I'm having trouble with using list initialization, any fixes with this error?

    It gives me the following errors:

    ---------------------------------
    Compiling...
    Quiz Chap1_5.cpp
    C:\Users\Desktop\Quiz Chap1_5.cpp(7) : error C2601: 'x' : local function definitions are illegal
    C:\Users\Desktop\Quiz Chap1_5.cpp(7) : error C2063: 'x' : not a function
    Error executing cl.exe.

    Quiz Chap1_5.obj - 2 error(s), 0 warning(s)
    ---------------------------------

    Can I just use copy initialization? Would there be any consequences for not using list initialization?

  • 51nevada

    why we put std:cout while we can write it directly
    cout<<
    is there a reason
    and how and when to use std if necessary

    • Straft

      cout is in std, and you can only access it through std::. However, you can do this:

      That way you never have to worry about std:: ever again!

  • Manjukrishna Suresh

    For Quiz 1b:
    Isn't the usage of direct list initialization supposed to cause the compiler to issue an error instead of dropping the fractional component in the above code?

  • Akash

    Hi,

    Quiz Question 1,

    a) A letter, such as h

    Why is x getting initialized to zero, should not it hold the ascii value of h instead ??

  • Bo

    Hi, I'm using eclispe 2020 and I'm getting a issue when I use the code in the quiz time example above. It keeps saying I'm missing a semi colon at the end on the line, int x{};. But if I remove the brackets completely and then add a semi colon it works with no issue. Here's the error itself below..

    Building file: ../main.cpp
    Invoking: GCC C++ Compiler
    g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.o" -o "main.o" "../main.cpp"
    ../main.cpp:38:11: error: expected ';' at end of declaration
                int x{}; // define variable x to hold user input
                     ^
                     ;
    1 error generated.
    make: *** [main.o] Error 1

    I have code above it but it's all been commented with the exception of the quiz time code.

    • nascardriver

      You need to enable C++11 or newer

      • J34NP3T3R

        can you clarify again ? right now i am on chapter 8.1 and while doing some practice on coding i realized i may have misunderstood what std::cin does

        basically all throughout the lessons until chapter 8.1 i thought std::cin accepts a character ( and a character only ) from user input and stores it in a variable.
        which is why if a user enters "abcde" instead of a character then std::cin will only take 'a' and leave 'bcde' in buffer.
        but while practicing i was surprised to see std::cin accepted 'abcde' and stored it in a string type variable.

        so now it appears to me that std::cin can accept multiple characters ( not separated by whitespaces ) depending on the variable if it can store the length of the input.
        if variable is CHAR type then cin will take 'a' and leave 'bcde' in buffer
        if variable is STRING type then cin will take 'abcde' and leave anything else starting from whitespace up to the end.

        is this correct ?

        • nascardriver

          `std::cin` can accept everything, provided the type defines how the extraction works.

          Fundamental types are built-in. `std::cin` knows how to read a character, an int, a float, etc.

          For class-types, like `std::string`, the authors of the class provide their own function that performs the extraction by using the built-in extraction functions. You'll later learn how to tell `std::cin` to read input into your own custom types.

      • I had the same issue as Bo (expected ';' at end of declaration) I was able to clear the error by doing the following:

        1) Open Eclipse IDE

        2) Go to: Project > Properties > C/C++ Build > Settings > Dialect

        3) Under the Dialect you can see Language Standard drop-down menu

        4) From the menu select the standard you wish to use

        (I enabled ISO C++20)

        Source: https://www.quora.com/How-do-I-enable-C-17-support-in-an-Eclipse-compiler?share=1

  • 3DartBlade

    I am new to c++ too, but I recommend creating a method to read the console such as:

    since that way you can instantly use the input value without defining a variable beforehand

    • Jay

      Calling an additional method is not as efficient and you are still declaring a variable within the function.

      • 3DartBlade

        Yeah, I think my notebook can handle that, and this way I can write less, but I'll keep that in mind if I ever need to make something really efficient. Thanks!

      • nascardriver

        This function will likely get inlined and therefore have 0 extra cost compared to not using a `Read()` function.
        Even if `Read()` does not get inlined, the function call overhead is minuscule and can almost always be neglected, definitely so in a context where we're reading user input. This is not a performance-critical part of the program.

        The benefit of going from 3 to 1 lines, and not having an uninitialized or value-initialized variable at the call-site is a good reason to use a `Read()` function.

  • Mark

    You note that some compilers, such as Visual Studio, will initialize the contents of memory when you’re using a debug build configuration, but that it will not do so when using a release build configuration. It would seem to me that this sort of behavior would defeat, at least in part, the purpose of having a debug build configuration because it would mask a serious potential problem that would have easily otherwise been detected in the debug build configuration if it worked operationally the same as the release build configuration. I understand that ideally one should initialize all variables, and if you do, this issue would be moot, but mistakes are made even by the best, let alone by the mediocre, especially if under the pressure of a timeline constraint. Am I missing something, or is Microsoft doing this simply to be consistent with the rest of their buggy and temperamental software products?

  • jason

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

    • nascardriver

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

  • Anonymous

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

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

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

    • nascardriver

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

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

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

      • Anonymous

        Thanks for the response!

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

        Also

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

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

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

        • nascardriver

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

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

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

          • Akash

            HI,

            I tried below infinite while loop, since i'm not using endl at the end of cout statement, it should have not printed anything, but i see that it keeps printing 0

            int main() {
              int i = 0;

              while(i < 1000000) {
                cout<<i;
              }

              cout<<endl;
            }

            • nascardriver

              It's partially implementation-defined when `std::cout` flushes its buffer. I doubt your `std::cout` is flushing each 0 separately. Try adding a sleep, you'll likely see that `std::cout` is printing your 0s in blocks, eg. whenever its buffer reached its limit.

          • He

            Sorry not sure why my last comment disappeared.

            Is there anyway to determine when exactly the data stored via cout will be printed to the screen?

            • nascardriver

              Your last comment is here https://www.learncpp.com/cpp-tutorial/introduction-to-iostream-cout-cin-and-endl/comment-page-6/#comment-501004

        • Satyo Jena

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

          • nascardriver

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

      • effy

        When you send something to a `cout` it's not printed immediately but stored in memory until some time later.

        I'm confused when it will be printed. Like is there a way to determine exactly when the data sent to `cout` will be printed?

        • nascardriver

          It will be printed when the buffer gets flushed. You can do that manually by using `std::endl` or `std::flush`, or let it happen automatically via tied streams (When you use `std::cin` or `std::cerr`, `std::cout` gets flushed). The buffer might also get flushed at any other point (eg. at every line feed), but that's implementation-defined.

  • N9

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

    • blackfox

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

  • qwerty

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

Leave a Comment

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