I/O Operations Console I/O
File I/O Formatting

C++ Input/Output: Complete Guide to cin, cout, and Streams

Master C++ Input/Output operations with comprehensive examples. Learn console I/O with cin and cout, file operations, stream formatting, and best practices for efficient I/O handling.

Input (cin)

Reading user input

Output (cout)

Displaying results

File I/O

Reading/writing files

Formatting

Custom output formats

C++ I/O Streams Overview

C++ uses streams for Input/Output operations. Streams are sequences of bytes that flow between your program and input/output devices (keyboard, screen, files). The iostream library provides the foundation for all I/O operations in C++.

cin Standard Input

Object of istream class for reading input from keyboard. Uses extraction operator >>.

cout Standard Output

Object of ostream class for writing output to screen. Uses insertion operator <<.

cerr Standard Error

Unbuffered stream for error messages. Output appears immediately without buffering.

clog Buffered Error

Buffered version of cerr for logging. More efficient for frequent error messages.

Key Concepts:
  • Streams: Abstraction for data flow between program and devices
  • Operators: >> for input (extraction), << for output (insertion)
  • Buffering: Temporary storage for efficiency (except cerr)
  • Header: #include <iostream> required for I/O operations

Basic Console Input/Output

1. Simple Input with cin

Basic cin Examples
#include <iostream>
using namespace std;

int main() {
    int age;
    double salary;
    string name;
    
    // Reading integer input
    cout << "Enter your age: ";
    cin >> age;
    
    // Reading multiple values
    cout << "Enter your name and salary: ";
    cin >> name >> salary;  // Space/tab/newline separates values
    
    cout << "\n--- Summary ---\n";
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Salary: $" << salary << endl;
    
    // Reading character input
    char grade;
    cout << "\nEnter your grade (A/B/C/D/F): ";
    cin >> grade;
    cout << "Grade: " << grade << endl;
    
    return 0;
}

2. Simple Output with cout

Basic cout Examples
#include <iostream>
#include <string>
using namespace std;

int main() {
    // Basic output
    cout << "Hello, World!" << endl;
    
    // Output variables
    int x = 10;
    double pi = 3.14159;
    string message = "Welcome to C++";
    
    cout << "x = " << x << endl;
    cout << "pi = " << pi << endl;
    cout << message << endl;
    
    // Chaining output
    cout << "Values: " << x << ", " << pi << ", " << message << endl;
    
    // Special characters
    cout << "Line 1\nLine 2\tTabbed\tText" << endl;
    cout << "Quotes: \"Hello\" Backslash: \\" << endl;
    
    // Calculations in output
    int a = 5, b = 3;
    cout << a << " + " << b << " = " << (a + b) << endl;
    cout << a << " * " << b << " = " << (a * b) << endl;
    
    return 0;
}
Important Notes:
  • cin skips leading whitespace (spaces, tabs, newlines)
  • cin >> stops reading at whitespace (can't read strings with spaces)
  • endl adds newline and flushes the output buffer
  • \n adds newline without flushing (more efficient)

Advanced Input Techniques

1. Reading Strings with Spaces (getline)

Using getline() for Strings with Spaces
#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    int age;
    
    cout << "Enter your age: ";
    cin >> age;
    
    // Clear the input buffer after reading age
    cin.ignore();  // Important! Removes the newline left by cin >>
    
    cout << "Enter your full name: ";
    getline(cin, fullName);  // Reads entire line including spaces
    
    cout << "\n--- User Information ---\n";
    cout << "Name: " << fullName << endl;
    cout << "Age: " << age << endl;
    
    // Multiple getline example
    string address, city;
    
    cout << "\nEnter your address: ";
    getline(cin, address);
    
    cout << "Enter your city: ";
    getline(cin, city);
    
    cout << "\nAddress: " << address << endl;
    cout << "City: " << city << endl;
    
    return 0;
}

2. Input Validation and Error Handling

Validating User Input
#include <iostream>
#include <limits>  // For numeric_limits
using namespace std;

int main() {
    int number;
    bool validInput = false;
    
    // Keep asking until valid input is provided
    while (!validInput) {
        cout << "Enter an integer between 1 and 100: ";
        
        if (cin >> number) {
            // Input is a valid integer
            if (number >= 1 && number <= 100) {
                validInput = true;
                cout << "Valid input: " << number << endl;
            } else {
                cout << "Error: Number must be between 1 and 100. Try again.\n";
            }
        } else {
            // Input is not an integer
            cout << "Error: Invalid input. Please enter an integer.\n";
            
            // Clear error flag
            cin.clear();
            
            // Discard invalid input
            cin.ignore(numeric_limits::max(), '\n');
        }
    }
    
    // Example with character validation
    char choice;
    cout << "\nDo you want to continue? (y/n): ";
    cin >> choice;
    
    // Convert to lowercase
    choice = tolower(choice);
    
    while (choice != 'y' && choice != 'n') {
        cout << "Invalid choice. Please enter 'y' or 'n': ";
        cin >> choice;
        choice = tolower(choice);
    }
    
    if (choice == 'y') {
        cout << "Continuing...\n";
    } else {
        cout << "Exiting...\n";
    }
    
    return 0;
}
Common cin Pitfalls:
  • Buffer Issues: Mixing cin >> and getline() without clearing buffer
  • Type Mismatch: Entering wrong data type causes stream error state
  • No Validation: Not checking if input operations succeed
  • Infinite Loops: Invalid input causing infinite loops without cin.clear()

Output Formatting and Manipulators

1. Formatting Numbers

Number Formatting Examples
#include <iostream>
#include <iomanip>  // For formatting manipulators
using namespace std;

int main() {
    double price = 99.9876;
    int number = 255;
    
    // Default formatting
    cout << "Default: " << price << endl;
    
    // Fixed-point notation with 2 decimal places
    cout << fixed << setprecision(2);
    cout << "Fixed (2 decimals): " << price << endl;
    
    // Show always show decimal point
    cout << showpoint << setprecision(3);
    cout << "Showpoint (3 decimals): " << 100.0 << endl;
    
    // Scientific notation
    cout << scientific << setprecision(4);
    cout << "Scientific: " << price << endl;
    
    // Reset to default
    cout.unsetf(ios::fixed | ios::scientific);
    cout << setprecision(6);  // Default precision
    
    // Integer formatting
    cout << "\n--- Integer Formatting ---\n";
    cout << "Decimal: " << number << endl;
    cout << hex << "Hexadecimal: " << number << endl;
    cout << oct << "Octal: " << number << endl;
    cout << dec;  // Reset to decimal
    
    // Field width and alignment
    cout << "\n--- Field Width ---\n";
    cout << setw(15) << left << "Name" 
         << setw(10) << right << "Age" 
         << setw(15) << right << "Salary" << endl;
    cout << setfill('-');
    cout << setw(40) << "" << endl;
    cout << setfill(' ');  // Reset fill
    
    cout << setw(15) << left << "John Doe" 
         << setw(10) << right << 25 
         << setw(15) << right << fixed << setprecision(2) << 55000.50 << endl;
    
    cout << setw(15) << left << "Jane Smith" 
         << setw(10) << right << 30 
         << setw(15) << right << 65000.75 << endl;
    
    // Boolean formatting
    cout << "\n--- Boolean Formatting ---\n";
    bool flag = true;
    cout << "Default: " << flag << endl;
    cout << boolalpha << "Boolalpha: " << flag << endl;
    cout << noboolalpha;  // Reset
    
    return 0;
}

2. Useful I/O Manipulators

Manipulator Description Example endl Insert newline and flush output buffer cout << "Hello" << endl; setw(n) Set field width for next output cout << setw(10) << num; setprecision(n) Set decimal precision for floating-point cout << setprecision(2) << price; fixed Use fixed-point notation cout << fixed << num; scientific Use scientific notation cout << scientific << num; left / right Set text alignment in field cout << left << setw(10) << text; setfill(c) Set fill character for padding cout << setfill('*') << setw(10) << num; boolalpha / noboolalpha Display booleans as true/false or 1/0 cout << boolalpha << flag;

File Input/Output

1. Basic File Operations

Reading from and Writing to Files
#include <iostream>
#include <fstream>   // File stream library
#include <string>
using namespace std;

int main() {
    // Writing to a file
    ofstream outFile("data.txt");  // Create/overwrite file
    
    if (!outFile) {
        cerr << "Error: Could not create file!" << endl;
        return 1;
    }
    
    outFile << "Student Records\n";
    outFile << "================\n";
    outFile << "Name: John Doe\n";
    outFile << "Age: 25\n";
    outFile << "GPA: 3.75\n";
    
    // Write formatted data
    outFile << fixed << setprecision(2);
    outFile << "Balance: $" << 1250.50 << endl;
    
    outFile.close();
    cout << "Data written to file successfully.\n\n";
    
    // Reading from a file
    ifstream inFile("data.txt");
    
    if (!inFile) {
        cerr << "Error: Could not open file for reading!" << endl;
        return 1;
    }
    
    string line;
    cout << "Reading file contents:\n";
    cout << "======================\n";
    
    while (getline(inFile, line)) {
        cout << line << endl;
    }
    
    inFile.close();
    
    // Appending to a file
    ofstream appFile("data.txt", ios::app);  // Open in append mode
    
    if (!appFile) {
        cerr << "Error: Could not open file for appending!" << endl;
        return 1;
    }
    
    appFile << "\nAdditional Record:\n";
    appFile << "Name: Jane Smith\n";
    appFile << "Age: 22\n";
    
    appFile.close();
    cout << "\nData appended to file successfully.\n";
    
    return 0;
}

2. File Modes and Error Handling

File Mode Description Example
ios::in Open for reading (default for ifstream) ifstream file("data.txt", ios::in);
ios::out Open for writing (default for ofstream) ofstream file("data.txt", ios::out);
ios::app Append to end of file ofstream file("data.txt", ios::app);
ios::ate Open and seek to end of file fstream file("data.txt", ios::ate);
ios::trunc Truncate file if it exists ofstream file("data.txt", ios::trunc);
ios::binary Open in binary mode ifstream file("data.bin", ios::binary);

Practical Examples

1. Student Grade Calculator

Complete Console Application
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
using namespace std;

int main() {
    string studentName;
    int numSubjects;
    double totalMarks = 0;
    
    cout << "╔═══════════════════════════════════════╗\n";
    cout << "║      STUDENT GRADE CALCULATOR        ║\n";
    cout << "╚═══════════════════════════════════════╝\n\n";
    
    // Get student name
    cout << "Enter student name: ";
    getline(cin, studentName);
    
    // Get number of subjects with validation
    while (true) {
        cout << "Enter number of subjects (1-10): ";
        if (cin >> numSubjects && numSubjects >= 1 && numSubjects <= 10) {
            break;
        } else {
            cout << "Invalid input! Please enter a number between 1 and 10.\n";
            cin.clear();
            cin.ignore(numeric_limits::max(), '\n');
        }
    }
    
    // Get marks for each subject
    cout << "\n─────────────────────────────────────\n";
    cout << "Enter marks for each subject (0-100):\n";
    
    for (int i = 1; i <= numSubjects; i++) {
        double marks;
        
        while (true) {
            cout << "Subject " << i << ": ";
            if (cin >> marks && marks >= 0 && marks <= 100) {
                totalMarks += marks;
                break;
            } else {
                cout << "Invalid marks! Please enter between 0 and 100.\n";
                cin.clear();
                cin.ignore(numeric_limits::max(), '\n');
            }
        }
    }
    
    // Calculate average
    double average = totalMarks / numSubjects;
    char grade;
    
    // Determine grade
    if (average >= 90) grade = 'A';
    else if (average >= 80) grade = 'B';
    else if (average >= 70) grade = 'C';
    else if (average >= 60) grade = 'D';
    else grade = 'F';
    
    // Display results with formatting
    cout << "\n════════════════════════════════════════\n";
    cout << "           GRADE REPORT               \n";
    cout << "════════════════════════════════════════\n\n";
    
    cout << left << setw(20) << "Student Name:" << studentName << endl;
    cout << left << setw(20) << "Number of Subjects:" << numSubjects << endl;
    cout << left << setw(20) << "Total Marks:" 
         << fixed << setprecision(2) << totalMarks << endl;
    cout << left << setw(20) << "Average Marks:" << average << endl;
    cout << left << setw(20) << "Grade:" << grade << endl;
    
    cout << "\n─────────────────────────────────────\n";
    
    // Save to file
    char saveChoice;
    cout << "\nSave results to file? (y/n): ";
    cin >> saveChoice;
    
    if (tolower(saveChoice) == 'y') {
        ofstream outFile("grade_report.txt", ios::app);
        if (outFile) {
            outFile << "─────────────────────────────────────\n";
            outFile << "Student: " << studentName << endl;
            outFile << "Average: " << fixed << setprecision(2) << average << endl;
            outFile << "Grade: " << grade << endl;
            outFile << "─────────────────────────────────────\n";
            outFile.close();
            cout << "Results saved to grade_report.txt\n";
        } else {
            cout << "Error: Could not save to file.\n";
        }
    }
    
    cout << "\nThank you for using the Grade Calculator!\n";
    
    return 0;
}

Best Practices & Tips

Input Best Practices
  • Always validate user input
  • Use getline() for strings with spaces
  • Clear buffer after cin >> before getline()
  • Check stream state after input operations
  • Provide clear prompts and error messages
Output Best Practices
  • Use \n instead of endl unless flushing is needed
  • Format output for readability
  • Separate data with clear delimiters
  • Use appropriate precision for numbers
  • Consider localization for international users
File I/O Best Practices
  • Always check if files open successfully
  • Close files when done (RAII helps with this)
  • Use appropriate file modes
  • Handle file errors gracefully
  • Consider using binary mode for non-text data

Summary & Quick Reference

Essential Headers
#include <iostream> - Standard I/O
#include <iomanip> - Formatting
#include <fstream> - File I/O
#include <string> - String handling
Performance Tips
  • Use \n instead of endl when possible
  • Avoid unnecessary cout calls in loops
  • Use string concatenation before output
  • Consider buffering for high-volume I/O

Final Tips

Mastering C++ I/O is essential for creating interactive programs. Start with simple cin/cout operations, then progress to file I/O and advanced formatting. Always handle errors gracefully and validate user input. Remember that efficient I/O can significantly impact your program's performance, especially in console applications.