Course outline · 0% complete

0/27 lessons0%

Course overview →

Printing with cout, Reading with cin

lesson 1-2 · ~9 min · 2/27

Everything in this course communicates through standard input and output: the isolated sandbox that runs your code feeds your program text on standard input and grades exactly what it prints to standard output. Getting fluent with cout and cin is not a warm-up — it is the interface every one of your solutions is judged through.

Chaining output

In lesson 1-1 you printed one string. << can be chained to print several things, of different types, in one statement:

int age = 24;
std::cout << "Age: " << age << " years\n";
// prints: Age: 24 years

Chaining works because << is an operation that returns the stream it just wrote to: std::cout << "Age: " << age first prints the string and hands back std::cout, and that returned stream is what << age writes to next. That is the actual rule that makes values come out strictly left to right. Numbers are converted to text automatically, so simple output needs no Python-style f-string formatting.

You will also see std::endl. It prints a newline like \n and additionally flushes the stream (forces the text out immediately). Prefer \n in normal code, it is faster.

Comments

// single-line comment
/* multi-line
   comment */

Code exercise · cpp

Run this program to see chained output mixing strings and numbers.

Reading input with cin

std::cin is the standard input stream, and >> extracts values from it:

int x;
std::cin >> x;   // reads one integer from input

Two things to notice:

  • You must declare the variable with its type first (int x;), then read into it. cin uses the type to know how to parse the text. This is the static typing we will dig into in lesson 1-3.
  • >> skips whitespace and newlines, so std::cin >> a >> b; happily reads 3 4 from one line or from two separate lines.

Compare with Python, where input() always gives you a string and you convert it yourself with int(...). In C++ the conversion happens automatically based on the variable's type.

Code exercise · cpp

Run this program. The input box already contains `Ada 36`. cin reads the word into a string and the number into an int.

Quiz

What does `std::cin >> a >> b;` do when the input is `10 20`?

Code exercise · cpp

Your turn. Read two integers from input and print their sum on one line. With input `3 4` the program must print exactly `Sum: 7`.