Basic Input & Output (cin/cout)

⚡ C++ Lesson 3 Beginner

C++ interacts with console streams using standard libraries. In this lesson, we will learn how to read variables, handle inputs safely, and format decimal outputs.

1 cin Streams and the Extraction (`>>`) Operator

The `std::cin` stream reads values from the console using the extraction operator (`>>`):

  • `std::cin >> age;`: Reads inputs until it encounters whitespace or a newline.
  • iomanip: The `<iomanip>` library formatting commands let you specify output decimal precision using `std::fixed` and `std::setprecision()`.
2 Dynamic Scanner Input

Let's run a program reading inputs and formatting floating decimal values:

C++ — Inputs & Formatting ▶ Run Code
#include <iostream>
#include <iomanip> // Needed for output formatting

int main() {
    int age;
    double price;

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

    std::cout << "Enter price: ";
    std::cin >> price;

    // Formatting decimal output to exactly 2 decimal places
    std::cout << "Age entered: " << age << "\n";
    std::cout << "Formatted Price: $" << std::fixed << std::setprecision(2) << price << "\n";

    return 0;
}
3 Code Challenge
Challenge: Write a program that asks the user to input their height in meters (e.g. `1.75`). Output the value to the screen formatted to exactly 3 decimal places using `setprecision`.