input-output


Include file: <iostream>

Introduction

The <iostream> header is a fundamental part of the C++ Standard Library that provides input and output functionality. It defines the standard input and output stream objects that allow programs to interact with the console and perform basic I/O operations.

Key Characteristics

Example 1: Basic Console Input and Output

#include <iostream>

int main() {
    std::string name;
    int age;

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

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

    std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;

    return 0;
}

Explanation

Example 2: Formatted Output with Manipulators

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.14159265358979323846;

    std::cout << "Default output: " << pi << std::endl;
    std::cout << "Fixed precision (3): " << std::fixed << std::setprecision(3) << pi << std::endl;
    std::cout << "Scientific notation: " << std::scientific << pi << std::endl;
    std::cout << "Hexadecimal: " << std::hex << std::uppercase << std::setw(10) << std::setfill('0') << 255 << std::endl;

    return 0;
}

Explanation

Example 3: Error Output and Input Validation

#include <iostream>
#include <limits>

int main() {
    int number;

    while (true) {
        std::cout << "Enter a positive integer: ";
        std::cin >> number;

        if (std::cin.fail() || number <= 0) {
            std::cerr << "Invalid input. Please try again." << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        } else {
            break;
        }
    }

    std::cout << "You entered: " << number << std::endl;

    return 0;
}

Explanation

Additional Notes

Summary

The <iostream> header is an essential component of C++ programming, providing the basic tools for console input and output. It defines the standard stream objects (cin, cout, cerr, and clog) and overloads the << and >> operators for various data types. This header enables developers to perform both formatted and unformatted I/O operations, with support for manipulators to control output formatting.

The examples provided demonstrate basic console I/O, formatted output using manipulators, and input validation techniques. These illustrations cover common use cases and showcase the versatility of the <iostream> library in handling different I/O scenarios.

Understanding and effectively using the <iostream> header is crucial for C++ programmers, as it forms the foundation for user interaction and data presentation in console applications. While more advanced I/O operations may require additional headers or libraries, <iostream> remains a cornerstone of C++ programming, especially for beginners and in educational contexts.

Previous Page | Course Schedule | Course Content