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. It is an object-oriented alternative to C's [C file input/output|]-based streams from the C standard library.
History
Bjarne Stroustrup, the creator of C++, wrote the first version of the stream I/O library in 1984, as a type-safe and extensible alternative to C's I/O library. The library has undergone a number of enhancements since this early version, including the introduction of manipulators to control formatting, and templatization to allow its use with character types other thanchar.Standardization in 1998 saw the library moved into the
std namespace, and the main header changed from to . It is this standardized version that is covered in the rest of the article.In C++20, the header
was added, adding std::format and std::formatter classes. In C++23, the header was added, which adds std::print and std::println, allowing for formatted printing to any output or file stream. These were both based on the existing fmtlib by Victor Zverovich.Overview
Most of the classes in the 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 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> , 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.
Header files
The classes of the input/output library reside in several headers.contains the definitions ofstd::ios_baseandstd::basic_iosclasses, that manage formatting information and the associated stream-buffer.contains the definition ofstd::basic_istreamclass template, which implements formatted input.contains the definition ofstd::basic_ostreamclass template, which implements formatted output.contains the definition ofstd::basic_iostreamclass template, which implements formatted input and output, and includes,and.contains the definitions ofstd::basic_ifstream,std::basic_ofstreamandstd::basic_fstreamclass templates which implement formatted input, output and input/output on file streams.contains the definitions ofstd::basic_istringstream,std::basic_ostringstreamandstd::basic_stringstreamclass templates which implement formatted input, output and input/output on string-based streams.contains formatting manipulators.contains forward declarations of all classes in the input/output library.provides improved input/output devices and streams forchar. These use astd::spanto the underlying buffer. This header supersedes the former.provides synchronised output devices and streams.contains format functions such asstd::formatand the definition of classesformatter,range_formatter, etc. and conceptformattable.contains the print functions, allowing for the printing of formatted strings to any output or file stream. It containsstd::printandstd::println, wherestd::printlnbehaves the same way asstd::print, except that each print is terminated by an additional new line.
was used for char input/output devices and streams. It is superseded by using std::stringstream and the header, and was removed in C++26.Stream buffers
There are twelve stream buffer classes defined in the C++ language as the table.Support classes
ios_base and basic_ios are two classes that manage the lower-level bits of a stream. ios_base stores formatting information and the state of the stream. basic_ios manages the associated stream-buffer. basic_ios is commonly known as simply ios or wios, which are two typedefs for basic_ios with a specific character type. basic_ios and ios_base are very rarely used directly by programmers. Usually, their functionality is accessed through other classes such as iostream which inherit them.Input/output streams
C++ input/output streams are primarily defined byiostream, 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, iostream provides basic input and output services for C++ programs. iostream uses the objects cin, cout, cerr, and clog for sending data to and from the standard streams input, output, error, and log respectively. As part of the C++ standard library, these objects are a part of the std namespace.The
cout object is of type 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 operations on the same ostream object, essentially as a different syntax for method cascading, exposing a fluent interface. The cerr and clog objects are also of type ostream, so they overload that operator as well. The cin object is of type 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.Output formatting
Manipulators
Manipulators are objects that can modify a stream using the<< or >> operators.endl | "end line": inserts a newline into the stream and calls flush. |
hex | "hexadecimal": all further numbers are printed in hexadecimal. |
dec | "decimal": turns off hexadecimal. |
ends | "end string": inserts a null character into the stream and calls flush. |
flush | forces an output stream to write any buffered characters |
ws | causes an inputstream to 'eat' whitespace |
showpoint | tells the stream to show the decimal point and some zeros with whole numbers |
Other manipulators can be found using the header
iomanip.Criticism
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 that a locale affects,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>. 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.Examples
The pre-C++23 canonical "Hello, World!" program which used the library, can be expressed as follows:- include
using std::endl;
int main
This program would output "Hello, world!" followed by a newline and standard output stream buffer flush.
The following example, which uses the
library, creates a file called '' and puts the text 'Hello, world!' followed by a newline into it.- include
using std::ostream;
int main
Using the
library added in C++23, the post-C++23 canonical "Hello, World!" program is expressed as:import std;
int main