Input/Output Operations

std::cin - Input

Input Demo

std::cout - Output

#include <iostream>

int main() {
    int x = 10;
    double y = 3.14;
    
    std::cout << "Value of x: " << x << std::endl;
    std::cout << "Value of y: " << y << std::endl;
    std::cout << "Sum: " << x + y << std::endl;
    
    return 0;
}

Basic Input/Output

#include <iostream>
#include <string>

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;
}

Formatted Output

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.14159265359;
    int number = 42;
    
    // Set precision for floating point
    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Pi to 2 decimal places: " << pi << std::endl;
    
    // Set field width and alignment
    std::cout << std::setw(10) << std::left << "Number: " << number << std::endl;
    
    // Hexadecimal output
    std::cout << "Number in hex: 0x" << std::hex << number << std::endl;
    
    return 0;
}

File Input/Output

#include <iostream>
#include <fstream>
#include <string>

int main() {
    // Writing to file
    std::ofstream outFile("output.txt");
    if (outFile.is_open()) {
        outFile << "Hello from C++!" << std::endl;
        outFile << "This is a test file." << std::endl;
        outFile.close();
        std::cout << "File written successfully!" << std::endl;
    }
    
    // Reading from file
    std::ifstream inFile("output.txt");
    std::string line;
    if (inFile.is_open()) {
        std::cout << "File contents:" << std::endl;
        while (std::getline(inFile, line)) {
            std::cout << line << std::endl;
        }
        inFile.close();
    }
    
    return 0;
}

String Streams

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string data = "John Doe 25 85.5";
    std::istringstream iss(data);
    
    std::string name, surname;
    int age;
    double score;
    
    iss >> name >> surname >> age >> score;
    
    std::cout << "Name: " << name << " " << surname << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Score: " << score << std::endl;
    
    return 0;
}