GO-V.ORG
As seen in

C++ input/output library

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 -based streams from the C standard library. Source: e01 Encyclopedia. Licence: CC BY-SA 4.0.

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 -based streams from the C standard library. ==Stream-based I/O library== The "Hello, World!" program using the features of the header can be expressed as follows: import std; int main() { std::cout This program would output " " followed by a newline and standard output stream buffer flush. The following example, which uses the features of the header, creates a file called ' ' and puts the text ' ' followed by a newline into it. import std; using std::ofstream; int main() { ofstream file("file.txt"); file ===Headers=== The classes of the input/output library reside in several headers. contains the definitions of std::ios_base and std::basic_ios classes, that manage formatting information and the associated stream-buffer. contains the definition of std::basic_istream class template, which implements formatted input. contains the definition of std::basic_ostream class template, which implements formatted output. contains the definition of std::basic_iostream class template, which implements formatted input and output, and includes , and . 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. 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. contains formatting manipulators. contains forward declarations of all classes in the input/output library. provides improved input/output devices and streams for char[] . These use a std::span to the underlying buffer. This header supersedes the former . provides synchronised output devices and streams. 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. ===Classes=== 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 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. ===Manipulators=== Manipulators are objects that can modify a stream using the or >> operators. Other manipulators can be found using the header. ===Input/output streams=== C++ input/output streams are primarily defined in (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 header inherited from C's (C's I/O library), 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. The objects are global objects with static duration tied to a static std::ios_base::Init instance (responsible for their construction and destruction). , 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). 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. ===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 (date, time or money) that a locale affects, and a statically linked "Hello, World!" program that uses of GNU libstdc++ produces an executable an order of magnitude larger than an equivalent program that uses . There exist partial implementations of the C++ standard library designed for space-constrained environments; their may leave out features that programs in such environments may not need, such as locale support. ==Formatter-based I/O library== Using the features of the header added in C++23, the "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 class which defined specializations for how a type is converted into text. 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 (which has specializations std::format_string for char and std::wformat_string for wchar_t ), which wraps over a std::basic_string_view , 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. 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. 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. ===Headers=== contains format functions such as std::format() and the definition of classes formatter , range_formatter , etc. and concept formattable . 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=== In stream-based I/O, custom formatting for a type T was done by overloading the stream insertion operator ostream& operator . Formatter-based I/O instead requires a specialization of the templated std::formatter , 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 and std::hash . import std; struct Vec2 { double x; double y; // Custom formatting flag enum class FormatMode { SHORT, FULL, }; }; namespace std { template <> struct formatter { 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 template <> struct formatter : public formatter { // parse() inherited automatically from formatter format_context::iterator format(const Vec2& v, format_context& ctx) const { string s = format("Vec2(x: {}, y: {})", v.x, v.y); return formatter ::format(v, ctx); } } } C++23 introduced range formatters , 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 to a std::range_format value: 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 = range_format::sequence; } ==See also== C file input/output printf C++ string handling ==References== ==External links== C++ reference for input/output library Apache C++ Standard Library Iostreams Comprehensive tutorial on formatting output in C++

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"C++ input/output library". 1789484335. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1375063429

JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy

Save to pass ·