Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Input/output (C++)

From Wikipedia, the free encyclopedia
C++ input/output functionality in the standard library

C++ Standard Library
Containers
C standard library

In theC++programming language,input/output library refers to a family ofclass templates and supporting functions in theC++ Standard Library that implement stream-based input/output capabilities.[1][2] It is anobject-oriented alternative to C'sFILE-based streams from theC standard library.[3][4]

History

[edit]

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 toC's I/O library.[5] 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 thestd namespace, and the main header changed from<iostream.h> to<iostream>. It is this standardized version that is covered in the rest of the article.

InC++20, the header<format> was added, addingstd::format() andstd::formatter classes.[6] InC++23, the header<print> was added, which addsstd::print() andstd::println(), allowing for formatted printing to any output or file stream.[7] These were both based on the existingfmtlib by Victor Zverovich.[8]

Overview

[edit]

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 severaltypedefs, 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 asfstream which is an alias forbasic_fstream<char,char_traits<char>>, or, in other words,basic_fstream working on characters of typechar 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.

ClassExplanationTypedefs
Stream buffers (low level functionality)
basic_streambufprovides abstract low level input/output interface, that can be implemented for concrete data sources or sinks. Rarely used directly.
  • streambuf – operates on characters of typechar
  • wstreambuf – operates on characters of typewchar_t
basic_filebufimplements low level input/output interface for file-based streams. Rarely used directly.
  • filebuf – operates on characters of typechar
  • wfilebuf – operates on characters of typewchar_t
basic_stringbufimplements low level input/output interface for string-based streams. Rarely used directly.
  • stringbuf – operates on characters of typechar
  • wstringbuf – operates on characters of typewchar_t
Support classes
ios_basemanages formatting information and exception stateN/a
basic_iosmanages a stream buffer
  • ios – operates on characters of typechar
  • wios – operates on characters of typewchar_t
Input streams buffers (high level functionality)
basic_istreamwraps an abstract stream buffer and provides high level input interface, such as formatting capabilities.
  • istream – operates on characters of typechar
  • wistream – operates on characters of typewchar_t
basic_ifstreaman 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 typechar
  • wifstream – operates on characters of typewchar_t
basic_istringstreaman 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 typechar
  • wistringstream – operates on characters of typewchar_t
Output streams buffers (high level functionality)
basic_ostreamwraps an abstract stream buffer and provides high level output interface, such as formatting capabilities.
  • ostream – operates on characters of typechar
  • wostream – operates on characters of typewchar_t
basic_ofstreaman 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 typechar
  • wofstream – operates on characters of typewchar_t
basic_ostringstreaman 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 typechar
  • wostringstream – operates on characters of typewchar_t
Input/output streams buffers (high level functionality)
basic_iostreamwraps an abstract stream buffer and provides high level input/output interface, such as formatting capabilities.
  • iostream – operates on characters of typechar
  • wiostream – operates on characters of typewchar_t
basic_fstreaman 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 typechar
  • wfstream – operates on characters of typewchar_t
basic_stringstreaman 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 typechar
  • wstringstream – operates on characters of typewchar_t

Header files

[edit]

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

  • <ios> contains the definitions ofstd::ios_base andstd::basic_ios classes, that manage formatting information and the associated stream-buffer.
  • <istream> contains the definition ofstd::basic_istream class template, which implements formatted input.
  • <ostream> contains the definition ofstd::basic_ostream class template, which implements formatted output.
  • <iostream> contains the definition ofstd::basic_iostream class template, which implements formatted input and output, and includes<ios>,<istream> and<ostream>.
  • <fstream> contains the definitions ofstd::basic_ifstream,std::basic_ofstream andstd::basic_fstream class templates which implement formatted input, output and input/output on file streams.
  • <sstream> contains the definitions ofstd::basic_istringstream,std::basic_ostringstream andstd::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 forchar[]. These use astd::span<CharT> to the underlying buffer. This header supersedes the former<strstream>.
  • <syncstream> provides synchronised output devices and streams.
  • <format> contains format functions such asstd::format() and the definition of classesformatter,range_formatter, etc. and conceptformattable.
  • <print> contains the print functions, allowing for the printing of formatted strings to any output or file stream. It containsstd::print() andstd::println(), wherestd::println() behaves the same way asstd::print(), except that each print is terminated by an additional new line.

<strstream> was used forchar[] input/output devices and streams. It is superseded by usingstd::stringstream and the<spanstream> header, and was removed inC++26.

Stream buffers

[edit]

There are twelve stream buffer classes defined in the C++ language as the table.

Further information:Seekg

Support classes

[edit]

ios_base andbasic_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 simplyios orwios, which are two typedefs forbasic_ios with a specific character type.basic_ios andios_base are very rarely used directly by programmers. Usually, their functionality is accessed through other classes such asiostream which inherit them.[9][10]

Typedefs

[edit]
Namedescription
iosconveniencetypedef for abasic_ios working with characters of typechar
wiosconvenience typedef for abasic_ios working with characters of typewchar_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

[edit]
NameDescription
boolalpha /noboolalphaspecifies whether variables of typebool appear astrue andfalse or as0 and1 in the stream.
skipws /noskipwsspecifies whether the white space is skipped in input operations
showbase /noshowbasespecifies whether the notational base of the number is displayed
showpoint /noshowpointspecifies whether to display the fractional part of a floating point number, when the fractional part is zero
showpos /noshowposspecifies whether to display+ for positive numbers
unitbuf /nounitbufspecifies whether the output should be buffered
uppercase /nouppercasespecifies whether uppercase characters should be used in hexadecimal integer and floating-point output
left /right /internalspecifies how a number should be justified
dec /oct/hexspecifies 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

[edit]
This article mayrequirecleanup to meet Wikipedia'squality standards. The specific problem is:Talks about a header, when it should talk about input/output streams. Please helpimprove this article if you can.(March 2012) (Learn how and when to remove this message)

C++input/output streams are primarily defined byiostream, aheader file that is part of theC++ standard library (the name stands forInput/OutputStream). In C++ and its predecessor, theC programming language, there is no special syntax for streaming data input or output. Instead, these are combined as alibrary offunctions. Like thecstdio header inherited from C'sstdio.h,iostream provides basic input and output services for C++ programs. iostream uses theobjectscin,cout,cerr, andclog for sending data to and from thestandard streams input, output, error (unbuffered), and log (buffered) respectively. As part of the C++standard library, these objects are a part of thestdnamespace.[11]

Thecout object is of typeostream, whichoverloads the leftbit-shiftoperator to make it perform an operation completely unrelated tobitwise operations, and notably evaluate to the value of the left argument, allowing multiple operations on the same ostream object, essentially as a different syntax formethod cascading, exposing afluent interface. Thecerr andclog objects are also of typeostream, so they overload that operator as well. Thecin object is of typeistream, 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

[edit]

Methods

[edit]
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

[edit]

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

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 ofdead code. For example, GNU libstdc++ automaticallyconstructs alocale when building anostream 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 anorder 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]

Naming conventions

[edit]
Main article:Standard streams

Examples

[edit]

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

#include<iostream>usingstd::cout;usingstd::endl;intmain(){cout<<"Hello, world!"<<endl;}

This program would output "Hello, world!" followed by anewline 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>usingstd::endl;usingstd::ostream;intmain(){ofstreamfile("file.txt");file<<"Hello, world!"<<endl;}

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

importstd;intmain(){std::println("Hello, world!");}

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. Retrieved1 December 2025.
  9. ^Stanley B. Lippman, Josee Lajoie (1999).C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp. 1112–1120.ISBN 0-201-82470-1.
  10. ^"<ios> Visual Studio 2010". Microsoft MSDN: Visual Studio 2010. Retrieved28 September 2011.
  11. ^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.
  12. ^GNU libstdc++ source code,bits/ios_base.h
  13. ^C++ vs. C – Pin Eight
  14. ^"uClibc++ C++ library". Retrieved6 January 2012.

External links

[edit]
Features
Standard Library
Ideas
Compilers
IDEs
Superset languages
Dialects
Relative to
other languages
People
Retrieved from "https://en.wikipedia.org/w/index.php?title=Input/output_(C%2B%2B)&oldid=1325383437"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp