C++ Basic Input / Output: Mastering cin, cout, cerr, clog & Manipulators

C++ uses the concept of Streams to perform input and output operations. A stream is an abstraction representing a sequence of bytes flowing into or out of your program. The header <iostream> provides four standard stream objects:

Stream Object Stream Type Device Buffering Description
std::cin istream Keyboard (Standard Input) Buffered Extracts formatted data from console
std::cout ostream Screen (Standard Output) Buffered Inserts formatted program data to console
std::cerr ostream Screen (Standard Error) Unbuffered Direct critical error output (never held in RAM)
std::clog ostream Screen / Log File Buffered Diagnostic event logging and auditing

Reading Strings with Spaces using std::getline

#include <iostream>
#include <string>

int main() {
    std::string fullName;
    int rollNumber;

    std::cout << "Enter student roll number: ";
    std::cin >> rollNumber;

    // CRITICAL: Consume the lingering newline character left by cin >>
    std::cin.ignore();

    std::cout << "Enter student full name: ";
    std::getline(std::cin, fullName);

    std::cout << "\n--- Student Profile ---\n";
    std::cout << "Roll No: " << rollNumber << "\n";
    std::cout << "Name:    " << fullName << "\n";

    return 0;
}

Stream Formatting Manipulators (<iomanip>)

#include <iostream>
#include <iomanip> // Required for manipulators

int main() {
    double price = 129.4567;

    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Formatted Price: $" << price << std::endl; // $129.46

    std::cout << std::setw(15) << std::setfill('*') << "Veewom" << std::endl; // *********Veewom
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between std::cout and std::cerr in C++?

std::cout is buffered standard output meant for normal program output. std::cerr is the unbuffered standard error stream that writes directly to the console immediately, ensuring error diagnostics are never lost if the program crashes.

Q2. Why does std::cin skip words when reading user strings?

The stream extraction operator (std::cin >> str) treats whitespace (spaces, tabs, newlines) as delimiters. To read an entire line with spaces, always use 'std::getline(std::cin, str)'.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Syntax

Understanding the stream insertion operator <<.

C++ File Streams

Applying streams to read and write files on disk.

C++ std::string

Reading multi-word text inputs with std::getline.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!