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 = output)
  • std::cin is used to get an input value (cin = 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

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

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

  • 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!

  • Dave

    Hello Alex! This site is awesome!

  • 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_

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

        • Alex

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

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

  • 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!!

  • Carol

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

  • 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. 🙂

  • 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".
    Cheers

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

  • 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 🙂

  • deepu

    Thanks for this awesome tutorial.

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

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

  • 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;
    }

  • 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. 😛

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

  • bob williams

    #include <iostream>

    // subtraction caculator
    int main()
    {
      std::cout << "Enter the first number: " << std::endl;
      int y = 0;
      cin.get();
      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:

  • 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

      Change

      to

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

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

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

  • 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:
    2
    10
    20

    Sample Output:
    1
    8
    22

    u can look at the problem here
    http://www.spoj.com/problems/DIVSUM/
    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.

  • 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"
    OR
    # include <iostream>

    Which one is (more) Correct?

  • Jim

    Alex,
    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.

  • 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

    • Alex

      The “std::cin >> x” line is waiting for you to enter a value for x from your keyboard. Once you do that and hit enter, your program should continue.

  • 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

      Try:

  • 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>InitializeBuildStatus:
    1>  Touching "Debug\std_cin.unsuccessfulbuild".
    1>ClCompile:
    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>
    1>Build FAILED.
    1>
    1>Time Elapsed 00:00:04.48
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  • 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?
    Is-

    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.

  • rookiecoder

    Hi.

    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.

  • Khan Md Sazzad Hossain Khan

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

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

    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

  • 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;
    }

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

  • Kattencrack Kledge

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

    Why is this happening?

  • KhangHcmut

    Thanks admin , nice !

  • 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…)

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

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

  • Erad

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

  • 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?

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

  • 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]

  • 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. 🙂

Leave a Comment

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