Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

C++ Input and Output — cout, cin, iomanip | Tutorials Logic

The iostream Library

C++ uses streams for I/O. A stream is a sequence of characters flowing to/from a device. The <iostream> header provides:

ObjectDirectionDescription
coutOutputStandard output (console) - use <<
cinInputStandard input (keyboard) - use >>
cerrOutputStandard error (unbuffered)
clogOutputStandard log (buffered)
cout - Output Formatting
#include <iostream>
#include <iomanip>   // setw, setprecision, fixed
using namespace std;

int main() {
    // Basic output
    cout << "Hello, World!" << endl;
    cout << "Line 1\nLine 2\n";  // \n is faster than endl

    // Chaining
    int a = 5, b = 10;
    cout << "a = " << a << ", b = " << b << endl;

    // Floating-point precision
    double pi = 3.14159265358979;
    cout << pi << endl;                          // 3.14159 (default 6 sig figs)
    cout << fixed << setprecision(2) << pi << endl;  // 3.14
    cout << fixed << setprecision(8) << pi << endl;  // 3.14159265

    // Column alignment with setw
    cout << left;  // left-align
    cout << setw(15) << "Name"  << setw(10) << "Score" << endl;
    cout << setw(15) << "Alice" << setw(10) << 95     << endl;
    cout << setw(15) << "Bob"   << setw(10) << 87     << endl;

    // Boolean output
    cout << boolalpha << true << " " << false << endl;  // true false

    // Hex / Oct / Dec
    int n = 255;
    cout << "Dec: " << dec << n << endl;  // 255
    cout << "Hex: " << hex << n << endl;  // ff
    cout << "Oct: " << oct << n << endl;  // 377

    return 0;
}
cin - Reading Input
#include <iostream>
#include <string>
using namespace std;

int main() {
    // Read a single word (stops at whitespace)
    string firstName;
    cout << "Enter first name: ";
    cin >> firstName;
    cout << "Hello, " << firstName << "!" << endl;

    // Read multiple values
    int age;
    double salary;
    cout << "Enter age and salary: ";
    cin >> age >> salary;
    cout << "Age: " << age << ", Salary: " << salary << endl;

    // Read a full line (including spaces)
    cin.ignore();  // discard leftover newline from previous cin
    string fullName;
    cout << "Enter full name: ";
    getline(cin, fullName);
    cout << "Full name: " << fullName << endl;

    // Input validation
    int num;
    cout << "Enter a number: ";
    if (cin >> num) {
        cout << "You entered: " << num << endl;
    } else {
        cerr << "Invalid input!" << endl;
    }

    return 0;
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.