close
Jump to content

C++ input/output library

From Wikipedia, the free encyclopedia
(Redirected from Input/output (C++))

In the C++ programming language, input/output library refers to a family of class templates and supporting functions in the C++ Standard Library that implement stream-based input/output capabilities.[1][2] It is an object-oriented alternative to C's FILE-based streams from the C standard library.[3][4]

History

[edit]

Bjarne Stroustrup, the creator of C++, wrote the first version of the stream I/O library in 1984, <stream.h>, as a type-safe and extensible alternative to C's I/O library, for his C with Classes language which would eventually evolve into C++.[5] The API overloaded the << and >> operators to indicate output and input.

Standardization in 1998 saw the library moved into the std namespace, and the main header changed from <iostream.h> to <iostream>.

In C++20, the header <format> was added, adding std::format() and std::formatter classes.[6] In C++23, the header <print> was added, which adds std::print() and std::println(), allowing for formatted printing to any output or file stream.[7] These were both based on the existing fmtlib by Victor Zverovich.[8] The API is similar to the C printf function (actually it matches Python's format) and is proving to be more popular as the code is more readable.

Stream-based I/O library

[edit]


The pre-C++23 canonical "Hello, World!" program which used the <iostream> library, can be expressed as follows:

#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
}

This program would output "Hello, world!" followed by a newline and standard output stream buffer flush.

The following example, which uses the <fstream> library, creates a file called 'file.txt' and puts the text 'Hello, world!' followed by a newline into it.

#include <fstream>

using std::ofstream;

int main() {
    ofstream file("file.txt");
    file << "Hello, world!" << std::endl;
}

Headers

[edit]

The classes of the input/output library reside in several headers.

  • <ios> contains the definitions of std::ios_base and std::basic_ios classes, that manage formatting information and the associated stream-buffer.
  • <istream> contains the definition of std::basic_istream class template, which implements formatted input.
  • <ostream> contains the definition of std::basic_ostream class template, which implements formatted output.
  • <iostream> contains the definition of std::basic_iostream class template, which implements formatted input and output, and includes <ios>, <istream> and <ostream>.
  • <fstream> contains the definitions of std::basic_ifstream, std::basic_ofstream and std::basic_fstream class templates which implement formatted input, output and input/output on file streams.
  • <sstream> contains the definitions of std::basic_istringstream, std::basic_ostringstream and std::basic_stringstream class templates which implement formatted input, output and input/output on string-based streams.
  • <iomanip> contains formatting manipulators.
  • <iosfwd> contains forward declarations of all classes in the input/output library.
  • <spanstream> provides improved input/output devices and streams for char[]. These use a std::span<CharT> to the underlying buffer. This header supersedes the former <strstream>.
  • <syncstream> provides synchronised output devices and streams.

<strstream> was used for char[] input/output devices and streams. It is superseded by using std::stringstream and the <spanstream> header, and was removed in C++26.

Classes

[edit]

Most of the classes in the stream-based I/O library are actually very generalized class templates. Each template can operate on various character types, and even the operations themselves, such as how two characters are compared for equality, can be customized. However, the majority of code needs to do input and output operations using only one or two character types, thus most of the time the functionality is accessed through several typedefs, which specify names for commonly used combinations of template and character type.

For example, basic_fstream<CharT, Traits> refers to the generic class template that implements input/output operations on file streams. It is usually used as fstream which is an alias for basic_fstream<char, char_traits<char>>, or, in other words, basic_fstream working on characters of type char with the default character operation set.

The classes in the library could be divided into roughly two categories: abstractions and implementations. Classes, that fall into abstractions category, provide an interface which is sufficient for working with any type of a stream. The code using such classes doesn't depend on the exact location the data is read from or is written to. For example, such code could write data to a file, a memory buffer or a web socket without a recompilation. The implementation classes inherit the abstraction classes and provide an implementation for concrete type of data source or sink. The library provides implementations only for file-based streams and memory buffer-based streams.

The classes in the library could also be divided into two groups by whether it implements low-level or high-level operations. The classes that deal with low-level stuff are called stream buffers. They operate on characters without providing any formatting functionality. These classes are very rarely used directly. The high-level classes are called streams and provide various formatting capabilities. They are built on top of stream buffers.

The following table lists and categorizes all classes provided by the input-output library.

Class Explanation Typedefs
Stream buffers (low level functionality)
basic_streambuf provides abstract low level input/output interface, that can be implemented for concrete data sources or sinks. Rarely used directly.
  • streambuf – operates on characters of type char
  • wstreambuf – operates on characters of type wchar_t
basic_filebuf implements low level input/output interface for file-based streams. Rarely used directly.
  • filebuf – operates on characters of type char
  • wfilebuf – operates on characters of type wchar_t
basic_stringbuf implements low level input/output interface for string-based streams. Rarely used directly.
  • stringbuf – operates on characters of type char
  • wstringbuf – operates on characters of type wchar_t
Support classes
ios_base manages formatting information and exception state N/a
basic_ios manages a stream buffer
  • ios – operates on characters of type char
  • wios – operates on characters of type wchar_t
Input streams buffers (high level functionality)
basic_istream wraps an abstract stream buffer and provides high level input interface, such as formatting capabilities.
  • istream – operates on characters of type char
  • wistream – operates on characters of type wchar_t
basic_ifstream an input stream that wraps a file stream buffer. Provides functions to open or close a file in addition to those of generic input stream
  • ifstream – operates on characters of type char
  • wifstream – operates on characters of type wchar_t
basic_istringstream an input stream that wraps a string stream buffer. Provides functions to access the underlying string in addition to those of generic input stream
  • istringstream – operates on characters of type char
  • wistringstream – operates on characters of type wchar_t
Output streams buffers (high level functionality)
basic_ostream wraps an abstract stream buffer and provides high level output interface, such as formatting capabilities.
  • ostream – operates on characters of type char
  • wostream – operates on characters of type wchar_t
basic_ofstream an output stream that wraps a file stream buffer. Provides functions to open or close a file in addition to those of generic output stream
  • ofstream – operates on characters of type char
  • wofstream – operates on characters of type wchar_t
basic_ostringstream an output stream that wraps a string stream buffer. Provides functions to access the underlying string in addition to those of generic output stream
  • ostringstream – operates on characters of type char
  • wostringstream – operates on characters of type wchar_t
Input/output streams buffers (high level functionality)
basic_iostream wraps an abstract stream buffer and provides high level input/output interface, such as formatting capabilities.
  • iostream – operates on characters of type char
  • wiostream – operates on characters of type wchar_t
basic_fstream an input/output stream that wraps a file stream buffer. Provides functions to open or close a file in addition to those of generic input/output stream
  • fstream – operates on characters of type char
  • wfstream – operates on characters of type wchar_t
basic_stringstream an input/output stream that wraps a string stream buffer. Provides functions to access the underlying string in addition to those of generic input/output stream
  • stringstream – operates on characters of type char
  • wstringstream – operates on characters of type wchar_t

Manipulators

[edit]

Manipulators are objects that can modify a stream using the << or >> operators.

Name Description
boolalpha / noboolalpha whether variables of type bool appear as true and false or as 0 and 1 in the stream.
skipws / noskipws whether the white space is skipped in input operations
showbase / noshowbase whether the notational base of the number is displayed
showpoint / noshowpoint whether to display the fractional part of a floating point number, when the fractional part is zero
showpos / noshowpos whether to display + before positive numbers
unitbuf / nounitbuf whether the output should be buffered
uppercase / nouppercase whether uppercase characters should be used in hexadecimal integer and floating-point output
left / right / internal how a number should be justified
dec / oct / hex the notation an integer number should be displayed in
fixed / scientific/
hexfloat /
defaultfloat
the notation a floating-point number should be displayed in
setw(int n)minimum number of CharT for next object
setfill(CharT c)character used to get the minimum number of CharT
setprecision(int n)sets the number of significant digits for floating-point numbers
endl"end line": inserts a newline into the stream and calls flush.
ends"end string": inserts a null character into the stream and calls flush.
flushforces an output stream to write any buffered characters
wscauses an inputstream to 'eat' whitespace
showpointtells the stream to show the decimal point and some zeros with whole numbers

Other manipulators can be found using the <iomanip> header.

Input/output streams

[edit]

C++ input/output streams are primarily defined in <iostream> (for "input/output stream"), a header file that is part of the C++ standard library. In C++ and its predecessor, the C programming language, there is no special syntax for streaming data input or output. Instead, these are combined as a library of functions. Like the <cstdio> header inherited from C's <stdio.h> (C's I/O library), <iostream> provides basic input and output services for C++ programs. iostream uses the objects std::cin, std::cout, std::cerr, and std::clog for sending data to and from the standard streams input, output, error (unbuffered), and log (buffered) respectively. As part of the C++ standard library, these objects are a part of the std namespace.[9]

The <iostream> objects are global objects with static duration tied to a static std::ios_base::Init instance (responsible for their construction and destruction).[10], which may be safely concurrently accessed from multiple threads for formatted and unformatted output (unless std::ios_base::sync_with_stdio(false) has been used).

Object Type Description
std::cin std::istream Reads from the stdin input stream
std::wcin std::wistream
std::cout std::ostream Writes to the stdout output stream
std::wcout std::wostream
std::cerr std::ostream Writes to the stderr output stream, unbuffered
std::wcerr std::wostream
std::clog std::ostream Writes to the stderr output stream, buffered (intended for logging)
std::wclog std::wostream

The std::cout object is of std::ostream, which overloads the left bit-shift operator to make it perform an operation completely unrelated to bitwise operations, and notably evaluate to the value of the left argument, allowing multiple chained operations on the same ostream object, essentially as a different syntax for method cascading (akin to a fluent interface). The std::cerr and std::clog objects are also of type std::ostream, so they overload that operator as well. The std::cin object is of type std::istream, which overloads the right bit-shift operator. The directions of the bit-shift operators make it seem as though data is flowing towards the output stream or flowing away from the input stream.

The class std::ios_base::Init is a class used to ensure the C++ streams (std::cin, std::cout, std::cerr, std::clog, and their wchar_t counterparts) are correctly initialized before use and flushed upon program termination.[11]

Criticism

[edit]

The formatting manipulators must be "reset" at the end or the programmer will unexpectedly get their effects on the next output statement.

Some implementations of the C++ standard library have significant amounts of dead code. For example, GNU libstdc++ automatically constructs a locale when building an ostream even if a program never uses any types (date, time or money) that a locale affects,[12] and a statically linked "Hello, World!" program that uses <iostream> of GNU libstdc++ produces an executable an order of magnitude larger than an equivalent program that uses <cstdio>.[13] There exist partial implementations of the C++ standard library designed for space-constrained environments; their <iostream> may leave out features that programs in such environments may not need, such as locale support.[14]

Formatter-based I/O library

[edit]

Using the <print> library added in C++23 (which is also imported by the standard library module std), the post-C++23 canonical "Hello, World!" program is expressed as:

import std;

int main() {
    std::println("Hello, world!");
}

The formatting library (introduced in C++20) introduced a new std::formatter<T, CharT> class which defined specializations for how a type is converted into text.[15] These formatters are used by functions like std::format() (which performs string formatting) and std::print()/std::println(), for printing text. Formatting requires a std::basic_format_string<CharT, Args...> (which has specializations std::format_string<Args...> for char and std::wformat_string<Args...> for wchar_t), which wraps over a std::basic_string_view<CharT>, for use on the following functions:

  • format(), which produces a string according to a format string and variadic arguments
  • format_to(), which formats a result to an output iterator according to a format string and variadic arguments
  • format_to_n(), which formats a result to an output iterator according to a format string and variadic arguments, writing at most n characters
  • formatted_size(), which returns a size_t counting the total number of CharT in the string returned by format().

std::dynamic_format(), introduced in C++26, returns an object that creates a dynamic formatting string usable in formatters. The dynamic format string type returned by dynamic_format() is not specified by the standard.[16]

The printing functions, introduced in C++23, added std::print() for printing to the output stream (or any file stream/std::ostream) using the formatted representation. std::println() does the same but appending a newline at the end.[17] These functions are variadic just like the C standard library's printf(), but use Python's formatter placeholder syntax (with {}) rather than printf()'s % specifiers, are type safe, and support custom types.[18]

Headers

[edit]
  • <format> contains format functions such as std::format() and the definition of classes formatter, range_formatter, etc. and concept formattable.
  • <print> contains the print functions, allowing for the printing of formatted strings to any output or file stream. It contains std::print() and std::println(), where std::println() behaves the same way as std::print(), except that each print is terminated by an additional new line.

Custom formatters

[edit]

In stream-based I/O, custom formatting for a type T was done by overloading the stream insertion operator ostream& operator<<(ostream& out, const T& x);. Formatter-based I/O instead requires a specialization of the templated std::formatter<T, CharT>, with two methods:

  • constexpr auto parse(auto& ctx) -> decltype(ctx)::iterator;, which extracts and validates the format string and flags at compile time (and is marked constexpr), processing everything between : and }
  • auto format(const T& x, auto& ctx) const -> decltype(ctx)::iterator;, which converts the object into text at runtime

Although it is illegal (undefined behavior) to add additional declarations or definitions to the std namespace, it is legal for certain template specializations, such as std::formatter<T, CharT> and std::hash<K>.[19]

import std;

struct Vec2 {
    double x;
    double y;

    // Custom formatting flag
    enum class FormatMode {
        SHORT,
        FULL,
    };
};

namespace std {
    template <>
    struct formatter<Vec2> {
        Vec2::FormatMode mode = Vec2::FormatMode::FULL;

        constexpr format_parse_context::iterator parse(format_parse_context& ctx) {
            auto it = ctx.begin();
            if (it != ctx.end() && (*it == 's' || *it == 'f')) {
                switch (*it) {
                    case 's':
                        mode = Vec2::FormatMode::SHORT;
                        break;
                    case 'f':
                        mode = Vec2::FormatMode::FULL;
                        break;
                    default:
                        unreachable();
                }
                ++it;
            }
            if (it != ctx.end() && *it != '}') {
                throw format_error("Invalid format specifier for Vec2");
            }
            return it;
        }

        format_context::iterator format(const Vec2& v, format_context& ctx) const {
            switch (mode) {
                case Vec2::FormatMode::SHORT:
                    return format_to(ctx.out(), "({}, {})", v.x, v.y);
                case Vec2::FormatMode::FULL:
                    return format_to(ctx.out(), "Vec2(x: {}, y: {})", v.x, v.y);
            }
            unreachable();
        }
    };
}

int main() {
    Vec2 pt{10, 20};
    std::println("Default: {}", pt);
    std::println("Short: {:s}", pt);
    std::println("Full: {:f}", pt);
}

Inheriting from an existing formatter allows the immediate reuse of standard format specifiers.

namespace std {
    // Inherit from formatter<string>
    template <>
    struct formatter<Vec2> : public formatter<string> {
        // parse() inherited automatically from formatter<string>

        format_context::iterator format(const Vec2& v, format_context& ctx) const {
            string s = format("Vec2(x: {}, y: {})", v.x, v.y);
            return formatter<string>::format(v, ctx);
        }
    }
}

C++23 introduced range formatters[20], allowing any type that defines begin() and end() to be formattable. It also formats pairs and tuples.

A style for printing a range type T can be chosen by setting std::format_kind<T>[21] to a std::range_format value:[22]

  • range_format::disabled: disables range default formatter
  • range_format::map: formats a range in map-representation with brackets and a colon separator
  • range_format::set: formats a range in set-representation with brackets
  • range_format::sequence: formats a range in sequence-representation with square brackets
  • range_format::string: formats a range as string
  • range_format::debug_string: formats a range as escaped string
// Defining a range formatter for an iterable Playlist class
namespace std {
    template <>
    constexpr range_format format_kind<Playlist> = range_format::sequence;
}

See also

[edit]

References

[edit]
  1. ISO/IEC 14882:2003 Programming Languages – C++. [lib.string.streams]/1
  2. Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp. 1109–1112. ISBN 0-201-82470-1.
  3. Bjarne Stroustrup (1997). The C++ programming language (third ed.). Addison-Wesley. pp. 637–640. ISBN 0-201-88954-4.
  4. Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp. 1063–1067. ISBN 0-201-82470-1.
  5. Bjarne Stroustrup. "A History of C++: 1979–1991" (PDF).
  6. Victor Zverovich (16 July 2019). "Text Formatting". open-std.org. WG 21.
  7. Victor Zverovich (25 March 2022). "Formatted output". open-std.org. WG 21.
  8. Victor Zverovich. "{fmt} - A modern formatting library". fmt.dev. fmtlib. Retrieved 1 December 2025.
  9. Holzner, Steven (2001). C++ : Black Book. Scottsdale, Ariz.: Coriolis Group. p. 584. ISBN 1-57610-777-9. ...endl, which flushes the output buffer and sends a newline to the standard output stream.
  10. cppreference.com. "Standard library header <iostream>". cppreference.com. cppreference.com. Retrieved 2 August 2026.
  11. cppreference.com. "std::ios_base::Init". cppreference.com. cppreference.com. Retrieved 2 August 2026.
  12. GNU libstdc++ source code, bits/ios_base.h
  13. C++ vs. C – Pin Eight
  14. "uClibc++ C++ library". Retrieved 6 January 2012.
  15. cppreference.com. "std::formatter". cppreference.com. cppreference.com. Retrieved 2 August 2026.
  16. cppreference.com. "std::dynamic_format". cppreference.com. cppreference.com. Retrieved 2 August 2026.
  17. cppreference.com. "Standard library header <print> (C++23)". cppreference.com. cppreference.com. Retrieved 2 August 2026.
  18. cppreference.com. "std::printf, std::fprintf, std::sprintf, std::snprintf". cppreference.com. cppreference.com.
  19. cppreference.com. "Extending the namespace std". cppreference.com. cppreference.com. Retrieved 3 August 2026.
  20. Barry Revzin (16 May 2022). "Formatting Ranges". open-std.org. WG 21.
  21. cppreference.com. "std::format_kind". cppreference.com. cppreference.com. Retrieved 3 August 2026.
  22. cppreference.com. "std::range_format". cppreference.com. cppreference.com. Retrieved 3 August 2026.
[edit]