HOME

TheInfoList



OR:

In the C++
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
, input/output library refers to a family of class templates and supporting functions in the
C++ Standard Library The C standard library, sometimes referred to as libc, is the standard library for the C programming language, as specified in the ISO C standard.ISO/ IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the origina ...
that implement stream-based input/output capabilities. It is an
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
alternative to C's FILE-based streams from the
C standard library The C standard library, sometimes referred to as libc, is the standard library for the C (programming language), C programming language, as specified in the ISO C standard.International Organization for Standardization, ISO/International Electrote ...
.


History

Bjarne Stroustrup Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, known for the development of the C++ programming language. He led the Large-scale Programming Research department at Bell Labs, served as a professor of computer sci ...
, 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 than char. 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 the
C++23 C++23, formally ISO/IEC 14882:2024, is the current open standard for the C++ programming language that follows C++20. The final draft of this version is N4950. In February 2020, at the final meeting for C++20 in Prague, an overall plan for C++ ...
revision, the header was added, which adds std::print() and std::println(), allowing for formatted printing to any output or file stream.


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
typedef typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (''alias'') for another data type, but does not create a new type, except in the obscure case of a qualified typedef of ...
s, 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 of ios_base and basic_ios classes, that manage formatting information and the associated stream-buffer. * contains the definition of basic_istream class template, which implements formatted input. * contains the definition of basic_ostream class template, which implements formatted output. * contains the definition of basic_iostream class template, which implements formatted input and output, and includes , and . * contains the definitions of basic_ifstream, basic_ofstream and basic_fstream class templates which implement formatted input, output and input/output on file streams. * contains the definitions of basic_istringstream, basic_ostringstream and basic_stringstream class 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. * 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.


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.


Typedefs


Formatting manipulators


Input/output streams

C++
input/output In computing, input/output (I/O, i/o, or informally io or IO) is the communication between an information processing system, such as a computer, and the outside world, such as another computer system, peripherals, or a human operator. Inputs a ...
streams are primarily defined by iostream, a
header file An include directive instructs a text file processor to replace the directive text with the content of a specified file. The act of including may be logical in nature. The processor may simply process the include file content at the location of ...
that is part of the
C++ standard library The C standard library, sometimes referred to as libc, is the standard library for the C programming language, as specified in the ISO C standard.ISO/ IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the origina ...
(the name stands for Input/Output Stream). In C++ and its predecessor, the
C programming language C (''pronounced'' '' – like the letter c'') is a general-purpose programming language. It was created in the 1970s by Dennis Ritchie and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of ...
, there is no special syntax for streaming data input or output. Instead, these are combined as a
library A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
of functions. Like the cstdio header inherited from C's
stdio.h The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header . The functionality descends from a "portable I/O package" written by Mike Lesk at ...
, iostream provides basic input and output services for C++ programs. iostream uses the
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an a ...
s cin, cout, cerr, and clog for sending data to and from the
standard streams In computer programming, standard streams are preconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), ...
input, output, error (unbuffered), and log (buffered) respectively. As part of the C++
standard library In computer programming, a standard library is the library (computing), library made available across Programming language implementation, implementations of a programming language. Often, a standard library is specified by its associated program ...
, these objects are a part of the std
namespace In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified. Namespaces ...
. 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 In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic opera ...
, 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 In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric ...
. 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


Methods


Manipulators

Manipulators are objects that can modify a stream using the << or >> operators. 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 The term dead code has multiple definitions. Some use the term to refer to code (i.e. instructions in memory) which can never be executed at run-time. In some areas of computer programming, dead code is a section in the source code of a program whi ...
. 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, and a statically linked
"Hello, World!" program A "Hello, World!" program is usually a simple computer program that emits (or displays) to the screen (often the Console application, console) a message similar to "Hello, World!". A small piece of code in most general-purpose programming languag ...
that uses <iostream> of GNU libstdc++ produces an executable an
order of magnitude In a ratio scale based on powers of ten, the order of magnitude is a measure of the nearness of two figures. Two numbers are "within an order of magnitude" of each other if their ratio is between 1/10 and 10. In other words, the two numbers are ...
larger than an equivalent program that uses <cstdio>.C++ vs. C – Pin Eight
/ref> 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.


Naming conventions


Examples

The pre-C++23 canonical
"Hello, World!" program A "Hello, World!" program is usually a simple computer program that emits (or displays) to the screen (often the Console application, console) a message similar to "Hello, World!". A small piece of code in most general-purpose programming languag ...
which used the library, can be expressed as follows: #include int main() This program would output "Hello, world!" followed by a
newline A newline (frequently called line ending, end of line (EOL), next line (NEL) or line break) is a control character or sequence of control characters in character encoding specifications such as ASCII, EBCDIC, Unicode, etc. This character, or ...
and standard output stream buffer flush. The following example, which uses the library, creates a file called 'file.txt' and puts the text 'Hello, world!' followed by a newline into it. #include int main() Using the 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; // Alternatively, if using headers instead of modules: // #include int main()


References


External links


C++ reference for input/output library



Comprehensive tutorial on formatting output in C++
{{DEFAULTSORT:Input output (C++) C++ C++ Standard Library Articles with example C++ code