Ch11.12.1: Complete C++ I/O Reference

Stream Classes

Class Description
std::istreamBase input stream
std::ostreamBase output stream
std::iostreamBase input/output stream
std::ifstreamInput file stream
std::ofstreamOutput file stream
std::fstreamInput/output file stream
std::istringstreamInput string stream
std::ostringstreamOutput string stream
std::stringstreamInput/output string stream
std::filebufFile buffer (narrow)
std::wfilebufFile buffer (wide)
std::streambufBase stream buffer

#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    // File streams
    std::ifstream in("input.txt");
    std::ofstream out("output.txt");
    std::fstream both("both.txt", std::ios::in | std::ios::out);

    // String streams
    std::istringstream sin("42 3.14");
    std::ostringstream sout;
    sout << "Value: " << 42;

    int x;
    double y;
    sin >> x >> y;

    std::cout << sout.str() << '\n';
    return 0;
}

Standard Stream Objects

Object Description
std::cinStandard input stream
std::coutStandard output stream
std::cerrStandard error stream (unbuffered)
std::clogStandard error stream (buffered)
std::wcinWide standard input stream
std::wcoutWide standard output stream
std::wcerrWide standard error stream (unbuffered)
std::wclogWide standard error stream (buffered)

Stream Manipulators

Manipulator Description
std::endlOutput newline and flush
std::endsOutput null terminator
std::flushFlush stream
std::wsSkip whitespace (input)
std::boolalphaUse true/false for booleans
std::noboolalphaUse 1/0 for booleans
std::showbaseShow base prefix (0x, 0)
std::noshowbaseDon’t show base prefix
std::showpointShow decimal point
std::noshowpointDon’t show decimal point
std::showposShow + sign for positive numbers
std::noshowposDon’t show + sign
std::skipwsSkip whitespace on input
std::noskipwsDon’t skip whitespace
std::uppercaseUse uppercase for hex/scientific
std::nouppercaseUse lowercase
std::unitbufFlush after each output
std::nounitbufDon’t flush after each output
std::internalInternal padding
std::leftLeft-align
std::rightRight-align
std::decDecimal base
std::hexHexadecimal base
std::octOctal base
std::fixedFixed-point notation
std::scientificScientific notation
std::defaultfloatDefault floating-point notation

#include <iostream>
#include <iomanip>

int main() {
    // Boolean formatting
    std::cout << std::boolalpha << true << '\n';  // true
    std::cout << std::noboolalpha << true << '\n';  // 1

    // Numeric base
    std::cout << std::hex << 255 << '\n';  // ff
    std::cout << std::showbase << std::hex << 255 << '\n';  // 0xff

    // Floating-point
    double pi = 3.14159;
    std::cout << std::fixed << pi << '\n';  // 3.141590
    std::cout << std::scientific << pi << '\n';  // 3.141590e+00

    // Alignment
    std::cout << std::left << std::setw(10) << 42 << "|\n";  // 42        |
    std::cout << std::right << std::setw(10) << 42 << "|\n";  //         42|

    return 0;
}