MODULE 2: C++ BASICS & CONTROL FLOW 2.3 C++ Input and Output Streams (`cin`, `cout`, `iomanip`)

Industrial reference manual: Detailed architectural breakdown of standard I/O streams in C++, stream insertion (`<<`) and extraction (`>>`) operators, formatting manipulators (`iomanip`), and 10 real-time production examples with outputs.

🖥️ Mastering C++ Standard I/O Streams (`<iostream>` & `<iomanip>`)

In C++, input and output are performed through streams—sequences of bytes flowing from devices (like keyboards) to programs or from programs to display monitors and files. Standard I/O is managed via the Header file `<iostream>`.

📥 Standard Input & Output Objects

  • std::cout: Standard output stream linked to the console (uses insertion operator `<<`).
  • std::cin: Standard input stream linked to the keyboard (uses extraction operator `>>`).
  • std::cerr: Unbuffered standard error stream for urgent diagnostic messages.
  • std::clog: Buffered standard logging stream for general program logs.

🎨 Formatting Manipulators (`<iomanip>`)

  • endl: Inserts newline and flushes the output buffer.
  • setprecision(n): Sets decimal precision for floating-point values.
  • setw(n): Sets minimum field width for output formatting.
  • fixed / scientific: Forces fixed-point or scientific notation formatting.

📊 End-to-End Standard I/O Stream & Buffer Pipeline Workflow Diagram

1. Keyboard Input

User enters raw text characters into standard input stream.

→

2. Extraction (`>>`)

`std::cin` extracts formatted tokens into target typed variables.

→

3. Variable Processing

CPU computes business logic, arithmetic, or validation checks.

↓

6. Console Rendering

Monitor displays formatted text, numbers, or alignment tables.

←

5. Stream Buffer (`endl`)

Flushes stream buffer to ensure immediate visual output.

←

4. Insertion (`<<`)

`std::cout` and `<iomanip>` format and push data to output buffer.

1. Interactive Profile Formatter (`std::cin` and `std::cout`)
Prompts the user for their name, age, and profession via standard input and prints a formatted user badge.
C++ / Interactive Profile Formatter
#include <iostream>
#include <string>

using namespace std;

int main() {
    // Simulated user input values for demonstration
    string fullName = "Aarav Sharma";
    int age = 26;
    string profession = "Software Engineer";

    cout << "--- Professional Identity Badge ---" << endl;
    cout << "Full Name : " << fullName << endl;
    cout << "Age       : " << age << " years" << endl;
    cout << "Profession: " << profession << endl;
    cout << "===================================" << endl;
    return 0;
}
--- Professional Identity Badge --- Full Name : Aarav Sharma Age : 26 years Profession: Software Engineer ===================================
2. Formatted Tax Invoice Table (`std::setw` and `std::left`/`std::right`)
Uses field width formatting (`std::setw`) and alignment manipulators to render a clean, professional billing table.
C++ / Formatted Billing Table
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    cout << "==============================================" << endl;
    cout << left  << setw(20) << "Item Description" 
         << right << setw(8)  << "Qty" 
         << right << setw(14) << "Total Price" << endl;
    cout << "----------------------------------------------" << endl;
    
    cout << left  << setw(20) << "Mechanical Keyboard" 
         << right << setw(8)  << "1" 
         << right << setw(14) << "₹4,500.00" << endl;
         
    cout << left  << setw(20) << "Gaming Mouse" 
         << right << setw(8)  << "2" 
         << right << setw(14) << "₹3,200.00" << endl;
         
    cout << "==============================================" << endl;
    return 0;
}
============================================== Item Description Qty Total Price ---------------------------------------------- Mechanical Keyboard 1 ₹4,500.00 Gaming Mouse 2 ₹3,200.00 ==============================================
3. Scientific & Fixed-Point Precision (`std::fixed`, `std::setprecision`)
Demonstrates how to control floating-point decimal precision for high-accuracy scientific and financial computations.
C++ / Precision Formatting
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    double piValue = 3.14159265358979323846;

    cout << "--- Precision Demonstration ---" << endl;
    cout << "Default output  : " << piValue << endl;
    cout << fixed << setprecision(2) << "Fixed (2 decimals): " << piValue << endl;
    cout << fixed << setprecision(6) << "Fixed (6 decimals): " << piValue << endl;
    cout << scientific << setprecision(4) << "Scientific notation: " << piValue << endl;
    return 0;
}
--- Precision Demonstration --- Default output : 3.14159 Fixed (2 decimals): 3.14 Fixed (6 decimals): 3.141593 Scientific notation: 3.1416e+00
4. Number Base Converter (`std::hex`, `std::oct`, `std::dec`)
Converts standard decimal integers into Hexadecimal, Octal, and Decimal output formats.
C++ / Number Base Formatting
#include <iostream>

using namespace std;

int main() {
    int decimalNumber = 255;

    cout << "--- Number Base Formatter ---" << endl;
    cout << "Decimal     : " << dec << decimalNumber << endl;
    cout << "Hexadecimal : " << hex << uppercase << decimalNumber << endl;
    cout << "Octal       : " << oct << decimalNumber << endl;
    return 0;
}
--- Number Base Formatter --- Decimal : 255 Hexadecimal : FF Octal : 377
5. Custom Filler Characters (`std::setfill`)
Pads output fields with custom characters like asterisks (`*`) or zeros (`0`) for receipt borders and serial codes.
C++ / Setfill Padding Example
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    int serialNumber = 42;

    cout << "--- Secured Serial Number ---" << endl;
    cout << "Padded with zeros : " << setfill('0') << setw(6) << serialNumber << endl;
    cout << "Padded with dashes: " << setfill('-') << setw(15) << "STATUS" << endl;
    return 0;
}
--- Secured Serial Number --- Padded with zeros : 000042 Padded with dashes: ---------STATUS
6. Error Logging with `std::cerr`
Demonstrates unbuffered standard error output (`std::cerr`) for reporting critical runtime exceptions.
C++ / Error Logging Stream
#include <iostream>

using namespace std;

int main() {
    double diskSpaceRemainingMb = 4.2;
    double minRequiredMb = 50.0;

    cout << "[INFO] Checking system storage requirements..." << endl;

    if (diskSpaceRemainingMb < minRequiredMb) {
        cerr << "[ERROR]: Critical low disk space! " 
             << diskSpaceRemainingMb << " MB available (Minimum required: " 
             << minRequiredMb << " MB)." << endl;
    } else {
        cout << "[SUCCESS] Storage check passed." << endl;
    }

    return 0;
}
[INFO] Checking system storage requirements... [ERROR]: Critical low disk space! 4.2 MB available (Minimum required: 50 MB).
7. Reading Multi-Word Strings with `std::getline`
Unlike `std::cin` which stops reading at the first space, `std::getline` captures entire sentences including spaces.
C++ / Multi-Word Input Capture
#include <iostream>
#include <string>

using namespace std;

int main() {
    // Simulated input string containing spaces
    string userAddress = "Flat No. 402, Silicon Heights, Baner, Pune";

    cout << "--- Delivery Address Registration ---" << endl;
    cout << "Registered Address: " << userAddress << endl;
    return 0;
}
--- Delivery Address Registration --- Registered Address: Flat No. 402, Silicon Heights, Baner, Pune
8. Stream Buffer Flushing (`std::flush` vs `std::endl`)
Demonstrates forcing output buffers to flush immediately without inserting a newline character using `std::flush`.
C++ / Stream Flushing Demonstration
#include <iostream>

using namespace std;

int main() {
    cout << "Connecting to Database server..." << flush;
    // simulated delay...
    cout << " [CONNECTED]" << endl;
    
    cout << "Loading configuration parameters..." << flush;
    // simulated delay...
    cout << " [LOADED]" << endl;

    return 0;
}
Connecting to Database server... [CONNECTED] Loading configuration parameters... [LOADED]
9. Boolean Text Alpha Formatting (`std::boolalpha`)
Forces boolean values to output as text (`true` / `false`) instead of integers (`1` / `0`).
C++ / Boolean Alpha Formatter
#include <iostream>

using namespace std;

int main() {
    bool isLoggedIn = true;
    bool hasAdminPrivileges = false;

    cout << "--- Authentication Flags ---" << endl;
    cout << "Numeric mode (default): " << isLoggedIn << ", " << hasAdminPrivileges << endl;
    
    cout << boolalpha;
    cout << "Alpha mode (boolalpha): " << isLoggedIn << ", " << hasAdminPrivileges << endl;
    return 0;
}
--- Authentication Flags --- Numeric mode (default): 1, 0 Alpha mode (boolalpha): true, false
10. Interactive Financial Loan Calculator Report
Combines input variables, arithmetic calculations, and formatted output streams to generate an EMI statement.
C++ / Loan EMI Statement Generator
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    double loanPrincipal = 500000.00; // ₹5 Lakhs
    double annualInterestRate = 8.5;  // 8.5%
    int tenureMonths = 36;            // 36 months

    double totalInterest = (loanPrincipal * (annualInterestRate / 100.0) * (tenureMonths / 12.0));
    double totalPayable = loanPrincipal + totalInterest;
    double monthlyEmi = totalPayable / tenureMonths;

    cout << "========================================" << endl;
    cout << "       NIKITA FINANCIAL LOAN EMI        " << endl;
    cout << "========================================" << endl;
    cout << fixed << setprecision(2);
    cout << left  << setw(18) << "Principal"     << ": ₹" << loanPrincipal << endl;
    cout << left  << setw(18) << "Total Interest"  << ": ₹" << totalInterest << endl;
    cout << left  << setw(18) << "Total Payable"   << ": ₹" << totalPayable << endl;
    cout << "----------------------------------------" << endl;
    cout << left  << setw(18) << "Monthly EMI"     << ": ₹" << monthlyEmi << " /month" << endl;
    cout << "========================================" << endl;
    return 0;
}
======================================== NIKITA FINANCIAL LOAN EMI ======================================== Principal : ₹500000.00 Total Interest : ₹127500.00 Total Payable : ₹627500.00 ---------------------------------------- Monthly EMI : ₹17430.56 /month ========================================