CodeBlanks Logo Icon CodeBlanks

std::cin

Learn to read input from the user with std::cin.

std::cin

std::cin is the standard input stream; it reads data from the keyboard. The >> operator writes data from the input stream into a variable. You first declare a variable, then read its value with std::cin >> var;.

For example, after declaring int age;, writing std::cin >> age; stores the number the user types into age. You can then print it with std::cout << age.

std::cin reads up to whitespace or a newline; you can read several values in a row with std::cin >> a >> b;.

Input and output with variables

In a real program, you store the value read by std::cin in a variable, then process and print it with std::cout. A variable is a box that holds a value by name.

In the example below, the age variable holds an integer; the user enters it and the program prints it:

int age = 25;
std::cout << "Age: " << age << std::endl;

Here the value is given directly as 25; in a real program it would be read with std::cin >> age;. You will learn variable declaration in detail in the next section.

Practice Print the age

Declare an int age variable and assign it 25 (in a real program you would read it with std::cin >> age;). Then use std::cout to produce the output Age: 25: print the string "Age: ", then the age variable, then std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare the age variable and assign 25
    // Print "Age: " and the age value with std::cout
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    // Declare the age variable and assign 25
    int age = 25;
    // Print "Age: " and the age value with std::cout
    std::cout << "Age: " << age << std::endl;
    return 0;
}

Expected output

Age: 25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the I/O concepts

Term Meaning
std::cin Input stream
>> Input operator
std::cout Output stream
<< Output operator

2 Input operator

Question
std::cin ____ age;
Answer
std::cin >> age;

Explanation: The >> operator reads from the input stream into a variable.

3 What does std::cin do?

  • It creates a file
  • It prints text to the screen
  • It compiles the program
  • It reads data from the keyboard Correct answer

Explanation: std::cin is the standard input stream and reads from the keyboard.

All lessons in Beginner