Skip to content

Input and Output with cin and cout

Programming C++ Difficulty 1/5

Beginning of the lesson

Input and Output with cin and cout

Talk to your program: print messages and read what the user types

Big Idea: A program becomes fun when it can talk with you. In C++, std::cout sends words and numbers out to the screen, and std::cin reads what the user types in from the keyboard. Together they let your program hold a real conversation.
By the end you will be able to:
  • print text and numbers with std::cout and the << operator,
  • read the user's input with std::cin and the >> operator,
  • chain several << or >> in one line,
  • start a new line with std::endl or "\n",
  • write a small interactive program.

1. Printing with std::cout

std::cout (say it "see-out") is the standard output stream. You push text into it with the << operator, and the text appears on the screen. To use it, include the <iostream> library at the top.

#include <iostream>

int main() {
    std::cout << "Hello, world!";
    return 0;
}

Output:

Hello, world!

The << arrows point toward cout, as if you are pushing the words into the screen.

2. Chaining with <<

You can print several things in one line by chaining <<. You can mix text (in quotes) and numbers (no quotes). The program prints them left to right, with no spaces added for you.

#include <iostream>

int main() {
    std::cout << "I am " << 9 << " years old!";
    return 0;
}

Output:

I am 9 years old!

Notice the spaces inside the quotes: "I am " and " years old!". If you forget them, the words and numbers stick together like I am9years old!.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers