Input/output (C++)

{{Short description|C++ standard library header for input/output}}

{{Use dmy dates|date=January 2022}}

{{C++ Standard 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.ISO/IEC 14882:2003 Programming Languages – C++. [lib.string.streams]/1{{cite book | title=C++ Primer | author=Stanley B. Lippman, Josee Lajoie | year=1999 | edition=third | publisher=Addison-Wesley | location=Massachusetts | pages=[https://archive.org/details/cprimer00lipp/page/1109 1109–1112] | isbn=0-201-82470-1 | url=https://archive.org/details/cprimer00lipp/page/1109 }} It is an object-oriented alternative to C's FILE-based streams from the C standard library.{{cite book | title=The C++ programming language | author=Bjarne Stroustrup | date=1997 | edition=third | publisher=Addison-Wesley | pages=[https://archive.org/details/cprogramminglang00stro_0/page/637 637–640] | isbn=0-201-88954-4 | url=https://archive.org/details/cprogramminglang00stro_0/page/637 }}{{cite book | title=C++ Primer | author=Stanley B. Lippman, Josee Lajoie | year=1999 | edition=third | publisher=Addison-Wesley | location=Massachusetts | pages=[https://archive.org/details/cprimer00lipp/page/1063 1063–1067] | isbn=0-201-82470-1 | url=https://archive.org/details/cprimer00lipp/page/1063 }}

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.{{cite web|url=http://www.stroustrup.com/hopl2.pdf|author=Bjarne Stroustrup|title=A History of C++: 1979–1991}} 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 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 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.

class=wikitable style="font-size:0.85em"
Class

! style="max-width:30em" | Explanation

! Typedefs

colspan=3 style="line-height:1em; padding: 0;" | 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.

| style="white-space:nowrap;" |

  • 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.

| style="white-space:nowrap;" |

  • 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.

| style="white-space:nowrap;" |

  • stringbuf – operates on characters of type char
  • wstringbuf – operates on characters of type wchar_t
colspan=3 style="line-height:1em; padding: 0;" | Support classes
ios_base

| manages formatting information and exception state

| {{n/a}}

basic_ios

| manages a stream buffer

| style="white-space:nowrap;" |

  • ios – operates on characters of type char
  • wios – operates on characters of type wchar_t
colspan=3 style="line-height:1em; padding: 0;" | Input streams buffers (high level functionality)
basic_istream

| wraps an abstract stream buffer and provides high level input interface, such as formatting capabilities.

| style="white-space:nowrap;" |

  • 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

| style="white-space:nowrap;" |

  • 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

| style="white-space:nowrap;" |

  • istringstream – operates on characters of type char
  • wistringstream – operates on characters of type wchar_t
colspan=3 style="line-height:1em; padding: 0;" | Output streams buffers (high level functionality)
basic_ostream

| wraps an abstract stream buffer and provides high level output interface, such as formatting capabilities.

| style="white-space:nowrap;" |

  • 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

| style="white-space:nowrap;" |

  • 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

| style="white-space:nowrap;" |

  • ostringstream – operates on characters of type char
  • wostringstream – operates on characters of type wchar_t
colspan=3 style="line-height:1em; padding: 0;" | 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.

| style="white-space:nowrap;" |

  • 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

| style="white-space:nowrap;" |

  • 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

| style="white-space:nowrap;" |

  • stringstream – operates on characters of type char
  • wstringstream – operates on characters of type wchar_t

=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.

{{Further|Seekg}}

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.{{cite book | title=C++ Primer | author=Stanley B. Lippman, Josee Lajoie | year=1999 | edition=third | publisher=Addison-Wesley | location=Massachusetts | pages=[https://archive.org/details/cprimer00lipp/page/1112 1112–1120] | isbn=0-201-82470-1 | url=https://archive.org/details/cprimer00lipp/page/1112 }}{{cite web | url=http://msdn.microsoft.com/en-us/library/5yc0df6d.aspx | title= Visual Studio 2010 | access-date=28 September 2011 | publisher=Microsoft MSDN: Visual Studio 2010}}

=Typedefs=

class="wikitable" style="font-size:0.85em"
Name || description
iosconvenience typedef for a basic_ios working with characters of type char
wiosconvenience typedef for a basic_ios working with characters of type wchar_t
streamoffsupports internal operations.
streamposholds the current position of the buffer pointer or file pointer.
wstreamposholds the current position of the buffer pointer or file pointer.
streamsizespecifies the size of the stream.

=Formatting manipulators =

class="wikitable" style="font-size:0.85em"
Name

! Description

boolalpha / noboolalpha

| specifies whether variables of type bool appear as true and false or as 0 and 1 in the stream.

skipws / noskipws

| specifies whether the white space is skipped in input operations

showbase / noshowbase

| specifies whether the notational base of the number is displayed

showpoint / noshowpoint

| specifies whether to display the fractional part of a floating point number, when the fractional part is zero

showpos / noshowpos

| specifies whether to display + for positive numbers

unitbuf / nounitbuf

| specifies whether the output should be buffered

uppercase / nouppercase

| specifies whether uppercase characters should be used in hexadecimal integer and floating-point output

left / right / internal

| specifies how a number should be justified

dec / oct/ hex

| specifies the notation an integer number should be displayed in

fixed / scientific/
hexfloat(C++11) /
defaultfloat(C++11)

| specifies the notation a floating-point number should be displayed in

Input/output streams

{{cleanup| reason=Talks about a header, when it should talk about input/output streams|date=March 2012}}

C++ input/output streams are primarily defined by iostream, a header file that is part of the C++ standard library (the name stands for Input/Output Stream). 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 (unbuffered), and log (buffered) respectively. As part of the C++ standard library, these objects are a part of the std namespace.{{cite book|last=Holzner|first=Steven|title=C++ : Black Book|year=2001|publisher=Coriolis Group|location=Scottsdale, Ariz.|isbn=1-57610-777-9|page=584|quote=...endl, which flushes the output buffer and sends a newline to the standard output stream.}}

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

=Methods=

class = wikitable
width(int x)minimum number of characters for next output
fill(char x)character used to fill with in the case that the width needs to be elongated to fill the minimum.
precision(int x)sets the number of significant digits for floating-point numbers

=Manipulators=

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

class=wikitable
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.
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 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 (date, time or money) that a locale affects,GNU libstdc++ source code, bits/ios_base.h

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>.[http://pineight.com/mw/index.php?title=C%2B%2B_vs._C#iostream C++ vs. C – Pin Eight] 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.{{cite web | url=http://cxx.uclibc.org/ | title=uClibc++ C++ library | access-date=6 January 2012}}

Naming conventions

{{main article|Standard streams}}

Examples

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

  1. include

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 library, creates a file called 'file.txt' and puts the text 'Hello, world!' followed by a newline into it.

  1. include

int main() {

std::ofstream file("file.txt");

file << "Hello, world!" << std::endl;

}

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() {

std::println("Hello, world!");

}

References

{{reflist}}