Search

1.3a — A first look at cout, cin, and endl

std::cout

As noted in previous sections, the std::cout object (in the iostream library) can be used to output text to the console. As a reminder, here’s our Hello world program:

To print more than one thing on the same line, the output operator (<<) can be used multiple times. For example:

This program prints:

x is equal to: 4

What would you expect this program to print?

You might be surprised at the result:

Hi!My name is Alex.

std::endl

If we want to print things to more than one line, we can do that by using std::endl. When used with std::cout, std::endl inserts a newline character (causing the cursor to go to the start of the next line).

For example:

This prints:

Hi!
My name is Alex.

std::cin

std::cin is the opposite of std::cout -- whereas std::cout prints data to the console using the output operator (<<), std::cin reads input from the user at the console using the input operator (>>). Now that you have a basic understanding of variables, we can use std::cin to get input from the user and store it in a variable.

Try compiling this program and running it for yourself. When you run the program, it will print “Enter a number: ” and then wait for you to enter one. Once you enter a number (and press enter), it 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 input from the user, and we will use it in many of our examples going forward.

If your screen closes immediately after entering a number, please see section 0.7 -- a few common cpp problems for a solution.

(As an interesting side note, if you enter a really big number, the results may surprise you. 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 section.)

std::cin, std::cout, <<, and >>

New programmers often mix up std::cin, std::cout, << and >>. Here’s an easy way to remember:

  • std::cin and 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 from the r-value 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 from the console into the variable. std::cin >> x moves the value from the console into x

(Admin note: Discussion of the std::namespace and using statements has been moved to lesson 1.8a -- Naming conflicts and the std namespace)

1.4 -- A first look at functions and return values
Index
1.3 -- A first look at variables, initialization, and assignment

126 comments to 1.3a — A first look at cout, cin, and endl

  • The Perplexed Programmer

    Hello Alex!

    Consider the above program. It asks for 2 input values, ul and ll. This is how the input looks like:
    1
    2
    If, however, I want it to look like
    1 2
    what should I be doing?

    In other words, I would like to input both the values in the same line.
    Please help!

  • Dear Teacher, please in second program

    add << std::endl between x and ;
    Regarding 3rd program vs 2017 community outputs
    Hi!My name is Alex.Appuyez sur une touche pour continuer… Regards (Regards is not output!).

    • Alex

      I haven’t talked about std::endl at this point (it’s lower in the lesson), hence my decision to omit it. You’re welcome to add it yourself though.

      Visual Studio 2017 adds the “Appuyez…” line when you run the program through the IDE to let you know it’s paused the output.

  • Nicholas

    Love these tutorials!! I made a simple addition calculator with the knowledge I have so far of C++ (addition calculator meaning it can only do addition). Here’s the code!

  • Mick

    Hi, thanks for the great tutorials, I’m really enjoying them.

    I’m working on an online ide, Codechef.

    When I run this programme, it doesn’t prompt me to enter a number, I just get: "Enter a number: You entered 0"

    Thank you for your help

    • Alex

      Maybe try a different online IDE and see if you get different results?

      • Mick

        Hi Alex

        Thanks for the quick reply. I tried ideone.com and got the same result, but then i tried repl.it and it worked so I’m back in business! I suspect it’s something to do with how the ide handles the input console.

        Thanks again

  • Hey @Alex, first of all… Awesome tutorial of C++!!!!
    And second you should specify that cout stands for "Character OUTput" and cin stands for "Character INput".

    And please tell me 2 or 3 books of C++ that you would recommend. Thanks again!

    • Alex

      I updated the lesson as you suggest. I don’t have any good books to recommend since there’s so much good information freely available on the internet these days.

  • Machinima Machinima

    cout
    - Console OUTput

    cin
    - Console INput

    endl
    - END Line

    some definitions which make it easier to remember what does what 🙂

  • Jonas

    Hello!!

    First of all a big thank you for this tutorial!! I’m new to programming and I find it easy to understand, so far.

    I encountered only one little problem. When I write code (using NetBeans8.2) and use the std::cin object and run the program it only kind of works.
    The user is asked to enter a number but when you press "enter" (Enter key) nothing happens. The program doesn’t continue.
    When you press any other key (a to z) it continues.

    Did anyone else ever have this problem? I find it pretty irritating since my instinct tells me to use the enter key after I entered something into a programm 🙂

    The code I used is the given one without the comments. I’ve checked countless times for errors and rewrote it a couple od times in different projects. The error is the same. And when I google it I only find results dealing with much more advanced problems.

    Thank you guys and girls in advance for any help given!

  • Christian Dingwell

    I see a widespread use of std::endl; and I can’t help wonder why?

    For me this works just fine:

    #include <iostream>

    using namespace std;

    int main()
    {
        cout << "Enter a number: ";
        int x = 0;
        cin >> x;
        cout << "You entered " << x;
        return 0;
    }

    Regards
    Christian

    • Alex

      Using statements are generally considered bad practice when used in the global scope.

      • Christian Dingwell

        Yes I’ll change that. But my question was about endl;

        It is pad practice not to use that as well? I don’t use it and my program works just fine.

        • Alex

          std::endl is used when we want to move the console cursor to the next line. You typically use it so you don’t have all your output run together. In a program with a single line of output, it’s technically not necessary, but I typically include it anyway, both out of habit and so I don’t have to go back and modify that line of code later if/when I add more output.

          Many people use ‘\n’ instead, and I discuss the pros and cons of that approach in chapter 2.

  • Sachin

    Is it compulsory to use std:: before cin and cout? Or its ok if i don’t write it.

    • Alex

      Best practice is to explicitly use the std:: prefix. There are ways to work around this by using “using statements” but it’s better to avoid them.

  • Chris

    I don’t understand why main is set to be an integer int main

  • hemanth kumar

    hello sir

    #include<iostream>
    int main()
    {
    std:: cout << "hello world"; << "hello world";
    return 0;
    }

    sir what is the problem when i like this

  • Mart

    Hi!

    Quick question

    Is there any advantage of using std::endl over just "\n".

    Thanks!

  • Devan

    Whenever I run the code through VS2015, it just runs the program but nothing pops up or prompts me like it used to… did I mess up something and can I fix it?

  • Mufti

    Hi Alex, Thank you for this tutorials

    please can you use one cin statement to assign values to several variables of different data types. if yes please how. thank once again.

    • Alex

      Enter 56a1.23 as input and you should get x=56, c=’a’, and d=1.23.

  • Hakim

    Alex, mate. You are an absolute legend! Love these tutorials and keep it up! PS: It’s awesome that you’re active in the comments section 🙂

  • Wyatt

    I know this is very simple, but is this a good example of a clean, well formatted program?

    I don’t fully understand floats yet, but I remember hearing somewhere that a float can hold a decimal value, so I tried replacing "int" with "float", & it worked.

    I’m really liking these tutorials so far, and I’d like to give myself a little "recap" with this program here. Input would be much appreciated!

  • eamon

    hullo alex!

    thanks for these tutorials, they’re great.

    i’m having a problem with the example code for std::cin - when i run it, all that appears in the console is this:

    "5Press any key to continue…"

    i press a key and the console closes.

    i pasted your code directly into visual studio - is there something i’m missing here?

    eamon

  • Bernat

    Hi, Alex.
    I tried something different. I just put pow(x,2) so I get the value I assign to x to the power of 2 and I tried what you said, to put a big number and see what happens, and everytime I try it my antivirus tells me that it has found an heuristic virus (I don’t know if these are the words in English but in Spanish it means that it doesn’t know what type of virus it is I think). For obvious reasons I guess it’s inoffensive, but I’d like to know why is it that my antivirus detects this piece of code as a potential menace.
    Thanks for this site. 🙂

  • Liam

    I get this error : /Error    1    error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup    c:Userswindowsdocumentsvisual studio 2013ProjectsProject2Project2MSVCRTD.lib(crtexew.obj)    Project2]

  • Hi Alex, can you please tell me the difference between "endl" and "\n"? I also want to know which one is better among them. I have seen many answers on Stack Overflow but I am still confused with that.

  • Logan39

    #include <iostream>
     
    int cout() // declares our own "cout" function
    {
        return 5;
    }
     
    int main()
    {
        using namespace std; // makes std::cout accessible as "cout"
        cout << "Hello, world!"; // uh oh!  Which cout do we want here?
     
        return 0;

    What does it mean having 5 as a return value? My understanding so far, was that you placed a zero return value, to end a program, and something about a zero being shown if the program has no errors. What is the basics of these return values, what does it all mean?

  • Erad

    Thanks Alex for your prompt reply! Keep up the good work!

  • Nguyen

    Hi Alex,

    The std namespace
    .
    .
    .
    We’ll talk more about namespaces in a future lesson and also teach you how to create your own…..
    .
    .
    .
    Could you please tell me what the future lesson is?
    The reason I am asking because I see a namespace(//define your own namespace to hold constants) in the last example of chapter 2.9.  I go back to every previous section to see if I could find it somewhere for my review (how to define your own namespace), I don’t see anything related.

    Thanks, Have a great day.

  • ali

    hi alex  
    1-you have said that cin and cout are functions live in std can we see what inside of them?
    2-can we see what inside of the object file (.o)?
    3-you are a very smart and Fabulous instructor do you have any other tutorial about Gui programming?

    • Alex

      1) I’m not aware of an easy way to see what’s inside of the std namespace through your IDE, however there are plenty of good references on the internet (see http://en.cppreference.com/)
      2) Not really. There are tools that will let you view the symbols in an object file, but you probably won’t ever need to use it.
      3) I don’t. I’d like to do some tutorials on GUI programming at some point, but there are so many other things I want to write about and so little time to write these days!

      • ali

        1)thank you very much.
        2)can you tell me where can I Find these tools it is out of Curiosity I just want to see how the compiler turns my code and how it looks like.
        3)can you give me the name of a good reference about GUI please.

        • Alex

          1) You’re welcome.
          2) It depends on your OS and compiler. If you’re using Windows/Visual Studio, check out https://msdn.microsoft.com/en-us/library/c1h23y6c.aspx
          3) I don’t know of a good, general purpose reference for this.

  • max

    What   return 0; means ??

    • Alex

      It means the function returns the value 0 back to the caller. The caller can then do whatever they want with this value (assign it, print it, ignore it, etc…)

  • KhangHcmut

    Thanks admin , nice !

  • Kattencrack Kledge

    In VS2015, including <iostream> before "stdafx.h" dosen’t include the functions/stuff in <iostream>:

    Why is this happening?

  • I have a little confusion over here!

    -----------------------------------

    PROGRAM:
    #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;
    }

    -----------------------------------

    We already told computer that integer x is equal to 0 (int x = 0;)!??! Really confusing please help me!

    • Alex

      For these two lines:

      The first line tells the compiler, “hey, we’re declaring a new variable called x, and initializing it with the value 0”.
      The second line tells the compiler, “hey, go ask the user for a new value for variable x”.

      So, in essence, x gets the value 0, then we overwrite it with whatever the user inputs.

  • Labib Enayet Azim

    Try this.The answer will always be 13. Remember to choose a number between 1 to 9.
    ____________________________________________________________________________________

    #include <iostream>

    using namespace std;

    int main()
    {
        cout << "Enter a number :";//ask use for a number
        int x = 0;
        cin >> x;//read number from console and store it in x
        cout << "You entered :" << x << endl;
        cout << "Please multiply the number by 9 and enter the answer :";
        cin >> x;
        cout << "You entered :" << x << endl;
        cout << "Please add the first and second digit of the number and enter the answer :";
        cin >> x;
        cout << "You entered :" << x << endl;
        cout << "Please add 4 to your new number :";
        cin >> x;
        cout << "You entered :" << x << endl;
        return 0;
    }

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter