• Home
  • 2.2 Reading Input Using std::cin

2.2 Reading Input Using std::cin

View Categories

2.2 Reading Input Using std::cin

1 min read

Table of Contents

The standard input stream is used to read data entered by the user. In C++, the object std::cin represents the standard input stream provided by the <iostream> library.

This example demonstrates how to read an integer value from the keyboard and display it on the console.

Source Code #

#include <iostream>

int main()
{
    int age;

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Age: " << age << '\n';

    return 0;
}

Output #

Enter your age: 25
Age: 25

Explanation #

  • int age; declares an integer variable that stores the value entered by the user.
  • std::cout << "Enter your age: "; displays a prompt before accepting input.
  • std::cin is the standard input stream object used to read data from the keyboard.
  • The extraction operator (>>) reads characters from the input stream, converts them to the required data type, and stores the result in age.
  • The extraction operator skips leading whitespace before reading the input value.
  • If the entered value cannot be converted to the target data type, the input operation fails and the stream enters the fail state.
  • std::cout << "Age: " << age << '\n'; prints the value stored in the variable.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *