cpp

examples

examples.cpp⚙️
/**
 * Module 01: Foundations
 * Topic: Input and Output
 * File: examples.cpp
 * 
 * This file demonstrates C++ I/O operations.
 * Study these examples after reading README.md.
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra examples.cpp -o examples
 * Run:     ./examples
 */

#include <iostream>
#include <iomanip>   // For setw, setprecision, etc.
#include <string>
#include <limits>    // For numeric_limits

using namespace std;

// ============================================================
// EXAMPLE 1: Basic Output with cout
// ============================================================
void example1_basic_output() {
    cout << "\n=== EXAMPLE 1: Basic Output ===" << endl;
    
    // Simple text output
    cout << "Hello, World!" << endl;
    
    // Chaining multiple outputs
    cout << "This " << "is " << "chained " << "output." << endl;
    
    // Output different types
    int age = 25;
    double price = 19.99;
    char grade = 'A';
    string name = "Alice";
    bool active = true;
    
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Price: $" << price << endl;
    cout << "Grade: " << grade << endl;
    cout << "Active: " << active << " (1=true, 0=false)" << endl;
}

// ============================================================
// EXAMPLE 2: endl vs \n
// ============================================================
void example2_newlines() {
    cout << "\n=== EXAMPLE 2: endl vs \\n ===" << endl;
    
    // Using endl (flushes buffer)
    cout << "Line 1 with endl" << endl;
    cout << "Line 2 with endl" << endl;
    
    // Using \n (no flush - slightly faster)
    cout << "Line 3 with \\n\n";
    cout << "Line 4 with \\n\n";
    
    // Multiple newlines
    cout << "Before two blank lines\n\n\nAfter two blank lines" << endl;
    
    // Flush without newline
    cout << "Processing" << flush;
    cout << "..." << flush;
    cout << " Done!" << endl;
}

// ============================================================
// EXAMPLE 3: Special Characters
// ============================================================
void example3_special_characters() {
    cout << "\n=== EXAMPLE 3: Special Characters ===" << endl;
    
    // Tab character
    cout << "Column1\tColumn2\tColumn3" << endl;
    cout << "Data1\tData2\tData3" << endl;
    
    // Quotes
    cout << "She said, \"Hello!\"" << endl;
    cout << "It\'s a nice day." << endl;
    
    // Backslash
    cout << "Path: C:\\Users\\Name\\Documents" << endl;
    
    // Carriage return (overwrites line)
    cout << "XXXXXXXXXX\rHello" << endl;  // Shows "HelloXXXXX"
    
    // Bell character (may beep)
    // cout << "Beep!\a" << endl;  // Uncomment to test
    
    // All escape sequences:
    cout << "\nEscape sequences:" << endl;
    cout << "\\n  - newline" << endl;
    cout << "\\t  - tab" << endl;
    cout << "\\\\  - backslash" << endl;
    cout << "\\\"  - double quote" << endl;
    cout << "\\'  - single quote" << endl;
    cout << "\\r  - carriage return" << endl;
}

// ============================================================
// EXAMPLE 4: Field Width and Alignment
// ============================================================
void example4_field_width() {
    cout << "\n=== EXAMPLE 4: Field Width and Alignment ===" << endl;
    
    // Default width (none)
    cout << "No width: [" << 42 << "]" << endl;
    
    // Set width to 10
    cout << "Width 10:  [" << setw(10) << 42 << "]" << endl;
    
    // Width with string
    cout << "Width 10:  [" << setw(10) << "Hello" << "]" << endl;
    
    // Left alignment
    cout << "Left:      [" << left << setw(10) << 42 << "]" << endl;
    
    // Right alignment (default)
    cout << "Right:     [" << right << setw(10) << 42 << "]" << endl;
    
    // Fill character
    cout << "Fill '*':  [" << setfill('*') << setw(10) << 42 << "]" << endl;
    cout << "Fill '0':  [" << setfill('0') << setw(10) << 42 << "]" << endl;
    
    // Reset fill
    cout << setfill(' ');
    
    // Creating a simple table
    cout << "\nSimple Table:" << endl;
    cout << setw(15) << left << "Name" 
         << setw(10) << "Age" 
         << setw(15) << "City" << endl;
    cout << string(40, '-') << endl;
    cout << setw(15) << "Alice" << setw(10) << 25 << setw(15) << "New York" << endl;
    cout << setw(15) << "Bob" << setw(10) << 30 << setw(15) << "Boston" << endl;
    cout << setw(15) << "Charlie" << setw(10) << 35 << setw(15) << "Chicago" << endl;
}

// ============================================================
// EXAMPLE 5: Floating-Point Formatting
// ============================================================
void example5_float_formatting() {
    cout << "\n=== EXAMPLE 5: Floating-Point Formatting ===" << endl;
    
    double pi = 3.14159265358979;
    double big = 123456.789;
    double small = 0.00000123;
    
    // Default output
    cout << "Default pi: " << pi << endl;
    
    // Set precision (total significant digits)
    cout << "\nPrecision (significant digits):" << endl;
    cout << "precision(3): " << setprecision(3) << pi << endl;
    cout << "precision(5): " << setprecision(5) << pi << endl;
    cout << "precision(10): " << setprecision(10) << pi << endl;
    
    // Fixed notation (digits after decimal)
    cout << "\nFixed notation:" << endl;
    cout << fixed;
    cout << "fixed precision(2): " << setprecision(2) << pi << endl;
    cout << "fixed precision(4): " << setprecision(4) << pi << endl;
    cout << "fixed big number: " << big << endl;
    
    // Scientific notation
    cout << "\nScientific notation:" << endl;
    cout << scientific;
    cout << "scientific pi: " << setprecision(2) << pi << endl;
    cout << "scientific big: " << big << endl;
    cout << "scientific small: " << small << endl;
    
    // Reset to default
    cout << defaultfloat << setprecision(6);
    cout << "\nBack to default: " << pi << endl;
    
    // Show decimal point always
    cout << "showpoint: " << showpoint << 100.0 << endl;
    cout << "noshowpoint: " << noshowpoint << 100.0 << endl;
}

// ============================================================
// EXAMPLE 6: Number Base Formatting
// ============================================================
void example6_number_bases() {
    cout << "\n=== EXAMPLE 6: Number Base Formatting ===" << endl;
    
    int num = 255;
    
    // Different bases
    cout << "Decimal:     " << dec << num << endl;
    cout << "Hexadecimal: " << hex << num << endl;
    cout << "Octal:       " << oct << num << endl;
    
    // Show base prefix
    cout << showbase;
    cout << "\nWith showbase:" << endl;
    cout << "Decimal:     " << dec << num << endl;
    cout << "Hexadecimal: " << hex << num << endl;
    cout << "Octal:       " << oct << num << endl;
    
    // Uppercase hex
    cout << uppercase;
    cout << "\nUppercase hex: " << hex << num << endl;
    
    // Reset
    cout << nouppercase << noshowbase << dec;
}

// ============================================================
// EXAMPLE 7: Boolean Formatting
// ============================================================
void example7_boolean_output() {
    cout << "\n=== EXAMPLE 7: Boolean Formatting ===" << endl;
    
    bool t = true;
    bool f = false;
    
    // Default (numeric)
    cout << "Default:" << endl;
    cout << "true = " << t << endl;
    cout << "false = " << f << endl;
    
    // Alpha (text)
    cout << boolalpha;
    cout << "\nWith boolalpha:" << endl;
    cout << "true = " << t << endl;
    cout << "false = " << f << endl;
    
    // Reset
    cout << noboolalpha;
}

// ============================================================
// EXAMPLE 8: Basic Input with cin
// ============================================================
void example8_basic_input() {
    cout << "\n=== EXAMPLE 8: Basic Input ===" << endl;
    
    // Note: Using simulated input for demonstration
    // In real usage, user would type these values
    
    cout << "Demonstrating input concepts (no actual input required):" << endl;
    
    // How basic input works:
    cout << R"(
    int age;
    cout << "Enter age: ";
    cin >> age;  // Reads until whitespace
    
    // Multiple inputs:
    int a, b, c;
    cin >> a >> b >> c;  // Can be on same line or different lines
    
    // Type conversion is automatic:
    double price;
    cin >> price;  // "19.99" becomes 19.99
    )" << endl;
    
    // Simulated example
    int simulatedAge = 25;
    cout << "Simulated: User entered age = " << simulatedAge << endl;
}

// ============================================================
// EXAMPLE 9: String Input - cin vs getline
// ============================================================
void example9_string_input() {
    cout << "\n=== EXAMPLE 9: String Input ===" << endl;
    
    cout << "Difference between cin >> and getline:\n" << endl;
    
    cout << "cin >> str:" << endl;
    cout << "  - Reads until whitespace" << endl;
    cout << "  - 'John Smith' would only give 'John'" << endl;
    cout << "  - Leaves rest in buffer" << endl;
    
    cout << "\ngetline(cin, str):" << endl;
    cout << "  - Reads entire line until Enter" << endl;
    cout << "  - 'John Smith' gives 'John Smith'" << endl;
    cout << "  - Consumes the newline" << endl;
    
    cout << "\nMixing cin >> and getline:" << endl;
    cout << R"(
    int age;
    string name;
    
    cin >> age;           // Reads number, leaves \n
    cin.ignore();         // Clear the newline!
    getline(cin, name);   // Now reads full name
    )" << endl;
}

// ============================================================
// EXAMPLE 10: Input Validation
// ============================================================
void example10_input_validation() {
    cout << "\n=== EXAMPLE 10: Input Validation ===" << endl;
    
    cout << "Input validation pattern:\n" << endl;
    
    cout << R"(
    int num;
    
    while (true) {
        cout << "Enter a positive number: ";
        
        if (cin >> num && num > 0) {
            break;  // Valid input
        }
        
        cout << "Invalid! Try again." << endl;
        cin.clear();  // Clear error state
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    
    cout << "You entered: " << num << endl;
    )" << endl;
    
    // Simulated validation
    cout << "\nSimulated validation:" << endl;
    cout << "User enters: 'abc' - Invalid!" << endl;
    cout << "User enters: '-5' - Invalid (not positive)!" << endl;
    cout << "User enters: '42' - Valid! Accepted." << endl;
}

// ============================================================
// EXAMPLE 11: Error Streams
// ============================================================
void example11_error_streams() {
    cout << "\n=== EXAMPLE 11: Error Streams ===" << endl;
    
    // Regular output
    cout << "This is normal output (cout)" << endl;
    
    // Error output (unbuffered)
    cerr << "This is error output (cerr)" << endl;
    
    // Log output (buffered)
    clog << "This is log output (clog)" << endl;
    
    cout << "\nDifferences:" << endl;
    cout << "  cout - buffered standard output" << endl;
    cout << "  cerr - unbuffered error output" << endl;
    cout << "  clog - buffered log output" << endl;
    
    cout << "\nRedirection in shell:" << endl;
    cout << "  ./program > out.txt     # Redirect cout" << endl;
    cout << "  ./program 2> err.txt    # Redirect cerr" << endl;
    cout << "  ./program > all.txt 2>&1  # Both to same file" << endl;
}

// ============================================================
// EXAMPLE 12: Practical Formatting - Receipt
// ============================================================
void example12_receipt() {
    cout << "\n=== EXAMPLE 12: Formatted Receipt ===" << endl;
    
    // Product data
    struct Product {
        string name;
        int qty;
        double price;
    };
    
    Product products[] = {
        {"Apple", 3, 0.50},
        {"Bread", 1, 2.99},
        {"Milk", 2, 3.49},
        {"Cheese", 1, 5.99}
    };
    
    double subtotal = 0;
    double taxRate = 0.08;
    
    // Print receipt
    cout << "\n";
    cout << setfill('=') << setw(45) << "" << setfill(' ') << endl;
    cout << setw(25) << "GROCERY STORE" << endl;
    cout << setw(27) << "123 Main Street" << endl;
    cout << setfill('=') << setw(45) << "" << setfill(' ') << endl;
    cout << endl;
    
    // Header
    cout << left;
    cout << setw(20) << "Item" 
         << setw(8) << "Qty" 
         << setw(10) << right << "Price" 
         << setw(10) << "Total" << endl;
    cout << setfill('-') << setw(45) << "" << setfill(' ') << endl;
    
    // Items
    cout << fixed << setprecision(2);
    for (const auto& p : products) {
        double total = p.qty * p.price;
        subtotal += total;
        
        cout << left << setw(20) << p.name
             << setw(8) << p.qty
             << right << setw(9) << p.price
             << setw(10) << total << endl;
    }
    
    // Totals
    cout << setfill('-') << setw(45) << "" << setfill(' ') << endl;
    
    double tax = subtotal * taxRate;
    double grandTotal = subtotal + tax;
    
    cout << left << setw(28) << "Subtotal:" << right << setw(17) << subtotal << endl;
    cout << left << setw(28) << "Tax (8%):" << right << setw(17) << tax << endl;
    cout << setfill('=') << setw(45) << "" << setfill(' ') << endl;
    cout << left << setw(28) << "TOTAL:" << right << setw(17) << grandTotal << endl;
    cout << setfill('=') << setw(45) << "" << setfill(' ') << endl;
    
    cout << "\n" << setw(27) << "Thank you!" << endl;
}

// ============================================================
// MAIN FUNCTION
// ============================================================
int main() {
    cout << "╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     C++ Input/Output - Examples                      ║" << endl;
    cout << "║     Study these after reading README.md              ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    example1_basic_output();
    example2_newlines();
    example3_special_characters();
    example4_field_width();
    example5_float_formatting();
    example6_number_bases();
    example7_boolean_output();
    example8_basic_input();
    example9_string_input();
    example10_input_validation();
    example11_error_streams();
    example12_receipt();
    
    cout << "\n╔══════════════════════════════════════════════════════╗" << endl;
    cout << "║     All examples completed!                          ║" << endl;
    cout << "║     Now try the exercises in exercises.cpp           ║" << endl;
    cout << "╚══════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}
Examples - C++ Tutorial | DeepML