苹果版Bitpie最新版app|iostream
cplusplus.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
TutorialsReferenceArticlesForum
Reference
C library:
C++11
C++11
C++11
C++11
C++11
C++11
Containers:
C++11
C++11
C++11
C++11
Input/Output:
Multi-threading:
C++11
C++11
C++11
C++11
C++11
Other:
C++11
C++11
C++11
C++11
C++11
C++11
C++11
C++11
C++11
C++11
objects
cerr
cin
clog
cout
wcerr
wcin
wclog
wcout
Reference
header
Standard Input / Output Streams Library
Header that defines the standard input/output stream objects:
Including this header may automatically include other headers, such as
Including
Note that the iostream class is mainly declared in header
Objects
Narrow characters (char)
cinStandard input stream (object)coutStandard output stream (object)cerrStandard output stream for errors (object)clogStandard output stream for logging (object)
Wide characters (wchar_t)
wcinStandard input stream (wide) (object)wcoutStandard output stream (wide) (object)wcerrStandard output stream for errors (wide-oriented) (object)wclogStandard output stream for logging (wide) (object)
Home page | Privacy policy© cplusplus.com, 2000-2023 - All rights reserved - v3.3.4s
Spotted an error? contact us
cplusplus.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
TutorialsReferenceArticlesForum
Reference
C library:
C++11
C++11
C++11
C++11
C++11
C++11
Containers:
C++11
C++11
C++11
C++11
Input/Output:
Multi-threading:
C++11
C++11
C++11
C++11
C++11
Other:
C++11
C++11
C++11
C++11
C++11
C++11
C++11
C++11
C++11
C++11
class templates
basic_iostream
basic_istream
classes
iostream
istream
wiostream
wistream
manipulators
ws
iostream
iostream::~iostream
iostream::iostream
protected members
C++11
iostream::operator=
C++11
iostream::swap
Reference
iostream
class
std::iostream
typedef basic_iostream
Input/output stream
ios_base
ios
istreamostream
iostream
fstreamstringstream
[NOTE: This page describes the iostream class, for a description of the iostream library, see Input/Output library.]
This is an instantiation of basic_iostream with the following template parameters:
template parameterdefinitioncomments
charTcharAliased as member char_type
traitschar_traits
This class inherits all members from its two parent classes istream and ostream, thus being able to perform both input and output operations.
The class relies on a single streambuf object for both the input and output operations.
Objects of these classes keep a set of internal fields inherited from ios_base, ios and istream:
fieldmember functionsdescription
Formattingformat flagsflagssetfunsetfA set of internal flags that affect how certain input/output operations are interpreted or generated.
See member type fmtflags.
field widthwidthWidth of the next formatted element to insert.
display precisionprecisionDecimal precision for the next floating-point value inserted.
localegetlocimbueThe locale object used by the function for formatted input/output operations affected by localization properties.
fill characterfillCharacter to pad a formatted field up to the field width (width).
Stateerror staterdstatesetstateclearThe current error state of the stream.
Individual values may be obtained by calling good, eof, fail and bad.
See member type iostate.
exception maskexceptionsThe state flags for which a failure exception is thrown.
See member type iostate.
Othercallback stackregister_callbackStack of pointers to functions that are called when certain events occur.
extensible arraysiwordpwordxallocInternal arrays to store objects of type long and void*.
tied streamtiePointer to output stream that is flushed before each i/o operation on this stream.
stream bufferrdbufPointer to the associated streambuf object, which is charge of all input/output operations.
character countgcountCount of characters read by last unformatted input operation (input streams only).
Member types
Member types char_type, traits_type, int_type, pos_type and off_type are ambiguous (multiple inheritance).
The class declares the following member types:
member typedefinition
char_typechar
traits_typechar_traits
int_typeint
pos_typestreampos
off_typestreamoff
These member types inherited from its base classes (istream, ostream and ios_base):
eventType to indicate event type (public member type)event_callbackEvent callback function type (public member type)failureBase class for stream exceptions (public member class)fmtflagsType for stream format flags (public member type)InitInitialize standard stream objects (public member class)iostateType for stream state flags (public member type)openmodeType for stream opening mode flags (public member type)seekdirType for stream seeking direction flag (public member type)istream::sentryPrepare stream for input (public member class)ostream::sentryPrepare stream for output (public member class)
Public member functions
(constructor)Construct object (public member function)(destructor)Destroy object (public member function)
Protected member functions
operator= Move assignment (protected member function)swap Swap internals (protected member function)
Public member functions inherited from istream
operator>>Extract formatted input (public member function)gcountGet character count (public member function)getGet characters (public member function)getlineGet line (public member function)ignoreExtract and discard characters (public member function)peekPeek next character (public member function)readRead block of data (public member function)readsomeRead data available in buffer (public member function)putbackPut character back (public member function)ungetUnget character (public member function)tellgGet position in input sequence (public member function)seekgSet position in input sequence (public member function)syncSynchronize input buffer (public member function)
Public member functions inherited from ostream
operator< Public member functions inherited from ios goodCheck whether state of stream is good (public member function)eofCheck whether eofbit is set (public member function)failCheck whether either failbit or badbit is set (public member function)badCheck whether badbit is set (public member function)operator!Evaluate stream (not) (public member function)operator bool Evaluate stream (public member function)rdstateGet error state flags (public member function)setstateSet error state flag (public member function)clearSet error state flags (public member function)copyfmtCopy formatting information (public member function)fillGet/set fill character (public member function)exceptionsGet/set exceptions mask (public member function)imbueImbue locale (public member function)tieGet/set tied stream (public member function)rdbufGet/set stream buffer (public member function)narrowNarrow character (public member function)widenWiden character (public member function) Public member functions inherited from ios_base flagsGet/set format flags (public member function)setfSet specific format flags (public member function)unsetfClear specific format flags (public member function)precisionGet/Set floating-point decimal precision (public member function)widthGet/set field width (public member function)imbueImbue locale (public member function)getlocGet current locale (public member function)xallocGet new index for extensible array [static] (public static member function)iwordGet integer element of extensible array (public member function)pwordGet pointer element of extensible array (public member function)register_callbackRegister event callback function (public member function)sync_with_stdioToggle synchronization with cstdio streams [static] (public static member function) Home page | Privacy policy© cplusplus.com, 2000-2023 - All rights reserved - v3.3.4s Spotted an error? contact us Input/output (C++) - Wikipedia Jump to content Main menu Main menu move to sidebar hide Navigation Main pageContentsCurrent eventsRandom articleAbout WikipediaContact usDonate Contribute HelpLearn to editCommunity portalRecent changesUpload file Search Search Create account Log in Personal tools Create account Log in Pages for logged out editors learn more ContributionsTalk Contents move to sidebar hide (Top) 1History 2Overview Toggle Overview subsection 2.1Header files 3Stream buffers 4Support classes Toggle Support classes subsection 4.1Typedefs 4.2Formatting manipulators 5Input/output streams 6Output formatting Toggle Output formatting subsection 6.1Methods 6.2Manipulators 7Criticism 8Naming conventions 9Examples 10References 11External links Toggle the table of contents Input/output (C++) 8 languages CatalàΕλληνικάEspañolفارسی한국어РусскийУкраїнська中文 Edit links ArticleTalk English ReadEditView history Tools Tools move to sidebar hide Actions ReadEditView history General What links hereRelated changesUpload fileSpecial pagesPermanent linkPage informationCite this pageGet shortened URLDownload QR codeWikidata item Print/export Download as PDFPrintable version From Wikipedia, the free encyclopedia C++ standard library header for input/output C++ Standard Library Input/output Strings algorithm functional Containers Sequence containers Associative containers Unordered associative containers C standard library Data types Character classification Strings Mathematics File input/output Date/time Localization Memory allocation Process control Signals Alternative tokens Miscellaneous headers: vte 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.[1][2] It is an object-oriented alternative to C's FILE-based streams from the C 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 to C'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 than char. Standardization in 1998 saw the library moved into the std namespace, and the main header changed from 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 several typedefs, which specify names for commonly used combinations of template and character type. For example, basic_fstream 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 Explanation Typedefs 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. 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. 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. stringbuf – operates on characters of type char wstringbuf – operates on characters of type wchar_t Support classes ios_base manages formatting information and exception state — basic_ios manages a stream buffer ios – operates on characters of type char wios – operates on characters of type wchar_t Input streams buffers (high level functionality) basic_istream wraps an abstract stream buffer and provides high level input interface, such as formatting capabilities. 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 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 istringstream – operates on characters of type char wistringstream – operates on characters of type wchar_t Output streams buffers (high level functionality) basic_ostream wraps an abstract stream buffer and provides high level output interface, such as formatting capabilities. 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 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 ostringstream – operates on characters of type char wostringstream – operates on characters of type wchar_t 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. 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 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 stringstream – operates on characters of type char wstringstream – operates on characters of type wchar_t Header files[edit] The classes of the input/output library reside in several headers. 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 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.[6][7] Typedefs[edit] Name description ios convenience typedef for a basic_ios working with characters of type char wios convenience typedef for a basic_ios working with characters of type wchar_t streamoff supports internal operations. streampos holds the current position of the buffer pointer or file pointer. wstreampos holds the current position of the buffer pointer or file pointer. streamsize specifies the size of the stream. Formatting manipulators[edit] 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[edit] This article may require cleanup to meet Wikipedia's quality standards. The specific problem is: Talks about a header, when it should talk about input/output streams. Please help improve this article if you can. (March 2012) (Learn how and when to remove this template message) 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.[8] 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[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. 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[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 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,[9] and a statically linked "Hello, World!" program that uses Naming conventions[edit] Main article: Standard streams Examples[edit] The canonical "Hello, World!" program can be expressed as follows: #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 creates a file called 'file.txt' and puts the text 'Hello, world!' followed by a newline into it. #include int main() { std::ofstream file("file.txt"); file << "Hello, world!" << std::endl; } References[edit] ^ ISO/IEC 14882:2003 Programming Languages – C++. [lib.string.streams]/1 ^ Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp. 1109–1112. ISBN 0-201-82470-1. ^ Bjarne Stroustrup (1997). The C++ programming language (third ed.). Addison-Wesley. pp. 637–640. ISBN 0-201-88954-4. ^ Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp. 1063–1067. ISBN 0-201-82470-1. ^ Bjarne Stroustrup. "A History of C++: 1979–1991" (PDF). ^ Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp. 1112–1120. ISBN 0-201-82470-1. ^ " ^ 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. ^ GNU libstdc++ source code, bits/ios_base.h ^ C++ vs. C – Pin Eight ^ "uClibc++ C++ library". Retrieved 6 January 2012. External links[edit] C++ reference for input/output library Apache C++ Standard Library Iostreams Comprehensive tutorial on formatting output in C++ Retrieved from "https://en.wikipedia.org/w/index.php?title=Input/output_(C%2B%2B)&oldid=1179941617" Categories: C++C++ Standard LibraryHidden categories: Articles with short descriptionShort description matches WikidataUse dmy dates from January 2022Articles needing cleanup from March 2012All pages needing cleanupCleanup tagged articles with a reason field from March 2012Wikipedia pages needing cleanup from March 2012Articles with example C++ code This page was last edited on 13 October 2023, at 13:07 (UTC). Text is available under the Creative Commons Attribution-ShareAlike License 4.0; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Privacy policy About Wikipedia Disclaimers Contact Wikipedia Code of Conduct Developers Statistics Cookie statement Mobile view Toggle limited content width Standard library header cppreference.com Log in Namespaces Page Discussion Variants Views View Edit History Actions Standard library header From cppreference.com < cpp | header C++ Compiler support Freestanding and hosted Language Standard library Standard library headers Named requirements Feature test macros (C++20) Language support library Concepts library (C++20) Metaprogramming library (C++11) Diagnostics library General utilities library Strings library Containers library Iterators library Ranges library (C++20) Algorithms library Numerics library Localizations library Input/output library Filesystem library (C++17) Regular expressions library (C++11) Concurrency support library (C++11) Technical specifications Symbols index External libraries [edit] Standard library headers Language support Concepts Diagnostics Memory management Metaprogramming General utilities Strings Containers (C++20) Iterators Ranges Algorithms Numerics Time Localization Input/output Regular expressions Concurrency support C compatibility [edit] This header is part of the Input/output library. Including Contents 1 Includes 2 Objects 3 Synopsis 4 Defect reports Includes std::ios_base class, std::basic_ios class template and several typedefs[edit] std::basic_streambuf class template[edit] std::basic_istream class template and several typedefs[edit] std::basic_ostream, std::basic_iostream class templates and several typedefs[edit] Objects cinwcin reads from the standard C input stream stdin(global object)[edit] coutwcout writes to the standard C output stream stdout(global object)[edit] cerrwcerr writes to the standard C error stream stderr, unbuffered(global object)[edit] clogwclog writes to the standard C error stream stderr(global object)[edit] [edit] Synopsis #include #include #include #include namespace std { extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; extern wistream wcin; extern wostream wcout; extern wostream wcerr; extern wostream wclog; } [edit] Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. DR Applied to Behavior as published Correct behavior LWG 155 C++98 the type of the static object was std::basic_ios::Init(not strictly wrong, but the wording was misleading) corrected to std::ios_base::Init LWG 1123 C++98 including guarantees Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/header/iostream&oldid=164046" Navigation Support usRecent changesFAQOffline version Toolbox What links hereRelated changesUpload fileSpecial pagesPrintable versionPermanent linkPage information In other languages Español日本語中文 This page was last modified on 27 November 2023, at 07:51. This page has been accessed 316,894 times. Privacy policy About cppreference.com Disclaimers 1.5 — Introduction to iostream: cout, cin, and endl – Learn C++Navigate1.6 — Uninitialized variables and undefined behaviorTable of contents1.4 — Variable assignment and initializationSite IndexLatest ChangesAboutSite FAQLeave feedbackReport an issueContact / SupportDonate SearchSearch for: SearchLearn C++Skill up with our free tutorialsSkip to contentNavigate1.6 — Uninitialized variables and undefined behaviorTable of contents1.4 — Variable assignment and initializationSite IndexLatest ChangesAboutSite FAQLeave feedbackReport an issueContact / SupportDonate SearchSearch for: Search1.5 — Introduction to iostream: cout, cin, and endlAlex January 12, 2015, 4:53 pm February 17, 2024In this lesson, we’ll talk more about std::cout, which we used in our Hello world! program to output the text Hello world! to the console. We’ll also explore how to get input from the user, which we will use to make our programs more interactive.The input/output libraryThe input/output library (io library) is part of the C++ standard library that deals with basic input and output. We’ll use the functionality in this library to get input from the keyboard and output data to the console. The io part of iostream stands for input/output.To use the functionality defined within the iostream library, we need to include the iostream header at the top of any code file that uses the content defined in iostream, like so:#include // rest of code that uses iostream functionality herestd::coutThe iostream library contains a few predefined variables for us to use. One of the most useful is std::cout, which allows us to send data to the console to be printed as text. cout stands for “character output”.As a reminder, here’s our Hello world program:#include int main() { std::cout << "Hello world!"; // print Hello world! to console return 0; }In this program, we have included iostream so that we have access to std::cout. Inside our main function, we use std::cout, along with the insertion operator (<<), to send the text Hello world! to the console to be printed.std::cout can not only print text, it can also print numbers:#include int main() { std::cout << 4; // print 4 to console return 0; }This produces the result:4 It can also be used to print the value of variables:#include int main() { int x{ 5 }; // define integer variable x, initialized with value 5 std::cout << x; // print value of x (5) to console return 0; }This produces the result:5 To print more than one thing on the same line, the insertion operator (<<) can be used multiple times in a single statement to concatenate (link together) multiple pieces of output. For example:#include int main() { std::cout << "Hello" << " world!"; return 0; }This program prints:Hello world! Here’s another example where we print both text and the value of a variable in the same statement:#include int main() { int x{ 5 }; std::cout << "x is equal to: " << x; return 0; }This program prints:x is equal to: 5 Related contentWe discuss what the std:: prefix actually does in lesson 2.9 -- Naming collisions and an introduction to namespaces.std::endlWhat would you expect this program to print?#include int main() { std::cout << "Hi!"; std::cout << "My name is Alex."; return 0; }You might be surprised at the result:Hi!My name is Alex. Separate output statements don’t result in separate lines of output on the console.If we want to print separate lines of output to the console, we need to tell the console when to move the cursor to the next line.One way to do that is to use std::endl. When output with std::cout, std::endl prints a newline character to the console (causing the cursor to go to the start of the next line). In this context, endl stands for “end line”.For example:#include int main() { std::cout << "Hi!" << std::endl; // std::endl will cause the cursor to move to the next line of the console std::cout << "My name is Alex." << std::endl; return 0; }This prints:Hi! My name is Alex. TipIn the above program, the second std::endl isn’t technically necessary, since the program ends immediately afterward. However, it serves a few useful purposes.First, it helps indicate that the line of output is a “complete thought” (as opposed to partial output that is completed somewhere later in the code). In this sense, it functions similarly to using a period in standard English.Second, it positions the cursor on the next line, so that if we later add additional lines of output (e.g. have the program say “bye!”), those lines will appear where we expect (rather than appended to the prior line of output).Third, after running an executable from the command line, some operating systems do not output a new line before showing the command prompt again. If our program does not end with the cursor on a new line, the command prompt may appear appended to the prior line of output, rather than at the start of a new line as the user would expect.Best practiceOutput a newline whenever a line of output is complete.std::cout is bufferedConsider a rollercoaster ride at your favorite amusement park. Passengers show up (at some variable rate) and get in line. Periodically, a train arrives and boards passengers (up to the maximum capacity of the train). When the train is full, or when enough time has passed, the train departs with a batch of passengers, and the ride commences. Any passengers unable to board the current train wait for the next one.This analogy is similar to how output sent to std::cout is typically processed in C++. Statements in our program request that output be sent to the console. However, that output is typically not sent to the console immediately. Instead, the requested output “gets in line”, and is stored in a region of memory set aside to collect such requests (called a buffer). Periodically, the buffer is flushed, meaning all of the data collected in the buffer is transferred to its destination (in this case, the console).Author’s noteTo use another analogy, flushing a buffer is kind of like flushing a toilet. All of your collected “output” is transferred to … wherever it goes next. Eew.This also means that if your program crashes, aborts, or is paused (e.g. for debugging purposes) before the buffer is flushed, any output still waiting in the buffer will not be displayed.Key insightThe opposite of buffered output is unbuffered output. With unbuffered output, each individual output request is sent directly to the output device.Writing data to a buffer is typically fast, whereas transferring a batch of data to an output device is comparatively slow. Buffering can significantly increase performance by minimizing the number of slow transfers that need to be performed when there are multiple output requests.std::endl vs ‘\n’Using std::endl can be a bit inefficient, as it actually does two jobs: it moves the cursor to the next line of the console, and it flushes the buffer. When writing text to the console, we typically don’t need to flush the buffer at the end of each line. It’s more efficient to let the system flush itself periodically (which it has been designed to do efficiently).Because of this, use of the ‘\n’ character is typically preferred instead. The ‘\n’ character moves the cursor to the next line of the console, but doesn’t request a flush, so it will often perform better. The ‘\n’ character is also more concise since it’s both shorter and can be embedded into existing text.Here’s an example that uses ‘\n’ in two different ways:#include int main() { int x{ 5 }; std::cout << "x is equal to: " << x << '\n'; // Using '\n' standalone std::cout << "And that's all, folks!\n"; // Using '\n' embedded into a double-quoted piece of text (note: no single quotes when used this way) return 0; }This prints:x is equal to: 5 And that's all, folks! When ‘\n’ is used by itself to move the cursor to the next line of the console, it should be single quoted. When embedded into text that is already double-quoted, additional quotes aren’t needed.We’ll cover what ‘\n’ is in more detail when we get to the lesson on chars (4.11 -- Chars).Best practicePrefer '\n' over std::endl when outputting text to the console.Warning'\n' uses a backslash (as do all special characters in C++), not a forward slash.Using a forward slash (e.g. '/n') or including other characters inside the single quotes (e.g. ' \n' or '.\n') will result in unexpected behavior. For example, std::cout << '/n'; will often print as 12142, which probably isn’t what you were expecting.std::cinstd::cin is another predefined variable that is defined in the iostream library. Whereas std::cout prints data to the console using the insertion operator (<<), std::cin (which stands for “character input”) reads input from keyboard using the extraction operator (>>). The input must be stored in a variable to be used.#include int main() { std::cout << "Enter a number: "; // ask user for a number int x{}; // define variable x to hold user input (and value-initialize it) std::cin >> x; // get number from keyboard and store it in variable x std::cout << "You entered " << x << '\n'; return 0; }Try compiling this program and running it for yourself. When you run the program, line 5 will print “Enter a number: “. When the code gets to line 8, your program will wait for you to enter input. Once you enter a number (and press enter), the number you enter will be assigned to variable x. Finally, on line 10, the program will print “You entered ” followed by the number you just entered.For example (I entered 4):Enter a number: 4 You entered 4 This is an easy way to get keyboard input from the user, and we will use it in many of our examples going forward. Note that you don’t need to use ‘\n’ when accepting input, as the user will need to press the enter key to have their input accepted, and this will move the cursor to the next line of the console.If your screen closes immediately after entering a number, please see lesson 0.8 -- A few common C++ problems for a solution.Just like it is possible to output more than one bit of text in a single line, it is also possible to input more than one value on a single line:#include int main() { std::cout << "Enter two numbers separated by a space: "; int x{}; // define variable x to hold user input (and value-initialize it) int y{}; // define variable y to hold user input (and value-initialize it) std::cin >> x >> y; // get two numbers and store in variable x and y respectively std::cout << "You entered " << x << " and " << y << '\n'; return 0; }This produces the output:Enter two numbers separated by a space: 5 6 You entered 5 and 6 Best practiceThere’s some debate over whether it’s necessary to initialize a variable immediately before you give it a user provided value via another source (e.g. std::cin), since the user-provided value will just overwrite the initialization value. In line with our previous recommendation that variables should always be initialized, best practice is to initialize the variable first.We’ll discuss how std::cin handles invalid input in a future lesson (9.5 -- std::cin and handling invalid input). For now, it’s enough to know that std::cin will extract as much as it can, and any input characters that could not be extracted are left for a later extraction attempt.For advanced readersThe C++ I/O library does not provide a way to accept keyboard input without the user having to press enter. If this is something you desire, you’ll have to use a third party library. For console applications, we’d recommend pdcurses, FXTUI, cpp-terminal, or notcurses. Many graphical user interface libraries have their own functions to do this kind of thing.SummaryNew programmers often mix up std::cin, std::cout, the insertion operator (<<) and the extraction operator (>>). Here’s an easy way to remember:std::cin and std::cout always go on the left-hand side of the statement.std::cout is used to output a value (cout = character output)std::cin is used to get an input value (cin = character input)<< is used with std::cout, and shows the direction that data is moving (if std::cout represents the console, the output data is moving from the variable to the console). std::cout << 4 moves the value of 4 to the console>> is used with std::cin, and shows the direction that data is moving (if std::cin represents the keyboard, the input data is moving from the keyboard to the variable). std::cin >> x moves the value the user entered from the keyboard into xWe’ll talk more about operators in lesson 1.9 -- Introduction to literals and operators.Quiz timeQuestion #1Consider the following program that we used above:#include int main() { std::cout << "Enter a number: "; // ask user for a number int x{}; // define variable x to hold user input std::cin >> x; // get number from keyboard and store it in variable x std::cout << "You entered " << x << '\n'; return 0; }The program expects you to enter an integer value, as the variable x that the user input will be put into is an integer variable.Run this program multiple times and describe what happens when you enter the following types of input instead:a) A letter, such as hShow Solutionx is 0.b) A number with a fractional component. Try numbers with fractional components less than 0.5 and greater than 0.5 (e.g. 3.2 and 3.7).Show SolutionThe fractional component is dropped.Since list initialization disallows narrowing conversions, new programmers are sometimes confused as to why the fraction is allowed to be dropped here. The initialization of x happens on line 6, and the restriction on narrowing conversions only applies to list initialization on this line. The user’s input is processed and assigned to x on line 7 (where such restrictions don’t apply because this statement is not a list initialization).c) A small negative integer, such as -3Show SolutionThis works fine.d) A word, such as HelloShow Solutionx is 0.e) A really big number (at least 3 billion)Show SolutionYou are most likely to get the number 2147483647. This happens because x can only hold numbers up to a certain size. If you enter a value larger than the largest number x can hold, it will be set to the largest number that x can hold (which is probably 2147483647, but might be different on your system). We discuss this further in lesson 4.4 -- Signed integers.f) A small number followed by some letters, such as 123abcShow Solutionx gets the numeric value (e.g. 123).Related contentWe discuss how std::cin and operator>> handle invalid input in future lesson 9.5 -- std::cin and handling invalid input.Next lesson1.6Uninitialized variables and undefined behaviorBack to table of contentsPrevious lesson1.4Variable assignment and initializationPrevious PostSite migrationNext Post2.4 — Introduction to function parameters and argumentsLabel Name* Email*Your email address will not be displayedFind a mistake? Leave a comment above!Correction-related comments will be deleted after processing to help reduce clutter. Thanks for helping to make the site better for everyone!Avatars from https://gravatar.com/ are connected to your provided email address.Notify me about replies: Label Name* Email*Your email address will not be displayedFind a mistake? Leave a comment above!Correction-related comments will be deleted after processing to help reduce clutter. Thanks for helping to make the site better for everyone!Avatars from https://gravatar.com/ are connected to your provided email address. 727 CommentsNewest Oldest Most VotedInline FeedbacksView all comments Load More Comments©2022 Learn C++wpDiscuzInsertYou are going to send email to SendMove CommentM | Microsoft Learn Skip to main content This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Download Microsoft Edge
More info about Internet Explorer and Microsoft Edge
Table of contents Exit focus mode Language Read in English Save Table of contents Read in English Save Edit Print Twitter LinkedIn Facebook Email Table of contents
Article 12/06/2021
8 contributors
Feedback In this article Declares objects that control reading from and writing to the standard streams. This include is often the only header you need to do input and output from a C++ program. Syntax #include Note The Remarks The objects fall into two groups: cin, cout, cerr, and clog are byte oriented, doing conventional byte-at-a-time transfers. wcin, wcout, wcerr, and wclog are wide oriented, translating to and from the wide characters that the program manipulates internally. Once you do certain operations on a stream, such as the standard input, you can't do operations of a different orientation on the same stream. Therefore, a program can't operate interchangeably on both cin and wcin, for example. All the objects declared in this header share a peculiar property — you can assume they're constructed before any static objects you define, in a translation unit that includes This guarantee isn't universal, however. A static constructor may call a function in another translation unit. The called function can't assume that the objects declared in this header have been constructed, given the uncertain order in which translation units participate in static construction. To use these objects in such a context, you must first construct an object of class ios_base::Init. Global Stream Objects Name Description cerr Specifies the cerr global stream. cin Specifies the cin global stream. clog Specifies the clog global stream. cout Specifies the cout global stream. wcerr Specifies the wcerr global stream. wcin Specifies the wcin global stream. wclog Specifies the wclog global stream. wcout Specifies the wcout global stream. cerr The object cerr controls output to a stream buffer associated with the object stderr, declared in extern ostream cerr; Return Value An ostream object. Remarks The object controls unbuffered insertions to the standard error output as a byte stream. Once the object is constructed, the expression cerr.flags & unitbuf is nonzero, and cerr.tie() == &cout. For more details, see cerr.flags and unitbuf. Example // iostream_cerr.cpp // compile with: /EHsc #include #include using namespace std; void TestWide( ) { int i = 0; wcout << L"Enter a number: "; wcin >> i; wcerr << L"test for wcerr" << endl; wclog << L"test for wclog" << endl; } int main( ) { int i = 0; cout << "Enter a number: "; cin >> i; cerr << "test for cerr" << endl; clog << "test for clog" << endl; TestWide( ); } cin Specifies the cin global stream. extern istream cin; Return Value An istream object. Remarks The object controls extractions from the standard input as a byte stream. Once the object is constructed, the call cin.tie returns &cout. Example In this example, cin sets the fail bit on the stream when it comes across non-numeric characters. The program clears the fail bit and strips the invalid character from the stream to continue. // iostream_cin.cpp // compile with: /EHsc #include using namespace std; int main() { int x; cout << "enter choice:"; cin >> x; while (x < 1 || x > 4) { cout << "Invalid choice, try again:"; cin >> x; // not a numeric character, probably // clear the failure and pull off the non-numeric character if (cin.fail()) { cin.clear(); char c; cin >> c; } } } 2 clog Specifies the clog global stream. extern ostream clog; Return Value An ostream object. Remarks The object controls buffered insertions to the standard error output as a byte stream. Example See cerr for an example of using clog. cout Specifies the cout global stream. extern ostream cout; Return Value An ostream object. Remarks The object controls insertions to the standard output as a byte stream. Example See cerr for an example of using cout. wcerr Specifies the wcerr global stream. extern wostream wcerr; Return Value A wostream object. Remarks The object controls unbuffered insertions to the standard error output as a wide stream. Once the object is constructed, the expression wcerr.flags & unitbuf is nonzero. For more details, see wcerr.flags and unitbuf. Example See cerr for an example of using wcerr. wcin Specifies the wcin global stream. extern wistream wcin; Return Value A wistream object. Remarks The object controls extractions from the standard input as a wide stream. Once the object is constructed, the call wcin.tie returns &wcout. Example See cerr for an example of using wcin. wclog Specifies the wclog global stream. extern wostream wclog; Return Value A wostream object. Remarks The object controls buffered insertions to the standard error output as a wide stream. Example See cerr for an example of using wclog. wcout Specifies the wcout global stream. extern wostream wcout; Return Value A wostream object. Remarks The object controls insertions to the standard output as a wide stream. Example See cerr for an example of using wcout. CString instances in a wcout statement must be cast to const wchar_t*, as shown in the following example. CString cs("meow"); wcout <<(const wchar_t*) cs < For more information, see Basic CString Operations. See also Header Files Reference Thread Safety in the C++ Standard Library iostream Programming iostreams Conventions Feedback Was this page helpful? Yes No Provide product feedback | Get help at Microsoft Q&A Feedback Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback. Submit and view feedback for This product This page View all page feedback Additional resources California Consumer Privacy Act (CCPA) Opt-Out Icon Your Privacy Choices Theme
Light
Dark
High contrast Previous Versions Blog Contribute Privacy Terms of Use Trademarks © Microsoft 2024 Additional resources In this article California Consumer Privacy Act (CCPA) Opt-Out Icon Your Privacy Choices Theme
Light
Dark
High contrast Previous Versions Blog Contribute Privacy Terms of Use Trademarks © Microsoft 2024 C++ iostream Courses Tutorials Examples Try Programiz PRO Course Index Explore Programiz Python JavaScript SQL HTML R C C++ Java RUST Golang Kotlin Swift C# DSA Learn C++ practically and Get Certified. ENROLL Popular Tutorials C++ if...else Statement C++ for Loop Arrays in C++ Strings in C++ C++ Class & Objects Start Learning C++ Popular Examples Create a simple calculator Check prime number Print the Fibonacci sequence Check if a number is palindrome or not Program to multiply matrix Explore C++ Examples Reference Materials iostream cmath cstring ctime View all Learning Paths Challenges Learn C++ Interactively Try for Free Courses Become a C++ Master Become a Python Master Become a C Master View all Courses Python JavaScript SQL HTML R C C++ Java More languages Learn C++ practically and Get Certified. ENROLL FOR FREE! Popular Tutorials C++ if...else Statement C++ for Loop Arrays in C++ Strings in C++ C++ Class & Objects Start Learning C++ All C++ Tutorials Reference Materials iostream cmath cstring ctime View all Python JavaScript R C C++ Java Kotlin Learn C++ practically and Get Certified. ENROLL FOR FREE! Popular Examples Create a simple calculator Check prime number Print the Fibonacci sequence Check if a number is palindrome or not Program to multiply matrix All C++ Examples C++ The C++ Search Functions C++ cerr Writes to error stream C++ cin accepts input from the user C++ clog used for streaming logs C++ cout displays output to output device i.e monitor C++ wcin accepts input in wide character type C++ wcout displays wide characters (Unicode) to screen Join our newsletter for the latest updates. This is required. Join Join our newsletter for the latest updates. This is required. Join Tutorials Python 3 Tutorial JavaScript Tutorial SQL Tutorial HTML Tutorial R Tutorial C Tutorial C++ Tutorial Java Tutorial Rust Tutorial Go Tutorial Kotlin Tutorial Swift Tutorial C# Tutorial DSA Tutorial Examples Python Examples JavaScript Examples C Examples Java Examples Kotlin Examples C++ Examples Company Change Ad Consent Do not sell my data About Advertising Privacy Policy Terms & Conditions Contact Blog Careers Youtube Apps Learn Python Learn C Programming Learn Java © Parewa Labs Pvt. Ltd. All rights reserved. cplusplus.com TUTORIALS REFERENCE ARTICLES FORUM C++ TutorialsReferenceArticlesForum Reference C library: C++11 C++11 C++11 C++11 C++11 C++11 Containers: C++11 C++11 C++11 C++11 Input/Output: Multi-threading: C++11 C++11 C++11 C++11 C++11 Other: C++11 C++11 C++11 C++11 C++11 C++11 C++11 C++11 C++11 C++11 Reference Input/Output library Input/Output Input/Output library The iostream library is an object-oriented library that provides input and output functionality using streams. A stream is an abstraction that represents a device on which input and ouput operations are performed. A stream can basically be represented as a source or destination of characters of indefinite length. Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard, or the console, so the characters gotten or written to/from our abstraction called stream are physically input/output to the physical device. For example, file streams are C++ objects to manipulate and interact with files; Once a file stream is used to open a file, any input or output operation performed on that stream is physically reflected in the file. To operate with streams, C++ provides the standard iostream library, which contains the following elements: Basic class templates The base of the iostream library is the hierarchy of class templates. The class templates provide most of the functionality of the library in a type-independent fashion. This is a set of class templates, each one having two template parameters: the char type (charT) parameter, that determines the type of elements that are going to be manipulated and the traits parameter, that provides additional characteristics specific for a particular type of elements. The class templates in this class hierarchy have the same name as their char-type instantiations but with the prefix basic_. For example, the class template which istream is instantiated from is called basic_istream, the one from which fstream is is called basic_fstream, and so on... The only exception is ios_base, which is by itself type-independent, and therefore is not based on a template, but is a regular class. Class template instantiations The library incorporates two standard sets of instantiations of the entire iostream class template hierarchy: one is narrow-oriented, to manipulate elements of type char and another one, wide-oriented, to manipulate elements of type wchar_t. The narrow-oriented (char type) instantiation is probably the better known part of the iostream library. Classes like ios, istream and ofstream are narrow-oriented. The diagram on top of this page shows the names and relationships of narrow-oriented classes. The classes of the wide-oriented (wchar_t) instatiation follow the same naming conventions as the narrow-oriented instantiation but with the name of each class and object prefixed with a w character, forming wios, wistream and wofstream, as an example. Standard objects As part of the iostream library, the header file They are divided in two sets: narrow-oriented objects, which are the popular cin, cout, cerr and clog and their wide-oriented counterparts, declared as wcin, wcout, wcerr and wclog. Types The iostream classes barely use fundamental types on their member's prototypes. They generally use defined types that depend on the traits used in their instantiation. For the default char and wchar_t instantiations, types streampos, streamoff and streamsize are used to represent positions, offsets and sizes, respectively. Manipulators Manipulators are global functions designed to be used together with insertion (<<) and extraction (>>) operators performed on iostream stream objects. They generally modify properties and formatting settings of the streams. endl, hex and scientific are some examples of manipulators. Organization The library and its hierarchy of classes is split in different files: Compatibility notes The names, prototypes and examples included in this reference for the iostream classes mostly describe and use the char instantiations of the class templates instead of the templates themselves, even though these classes are only one of their possible instantiations. We believe this provides a better readability and is arguably as easy to obtain the names and prototypes of the basic template from the char instantiation as the opposite. Elements of the iostream library (char instantitation) Classes: ios_baseBase class for streams (class)iosBase class for streams (type-dependent components) (class)istreamInput stream (class)ostreamOutput Stream (class)iostreamInput/output stream (class)ifstreamInput file stream class (class)ofstreamOutput file stream (class)fstreamInput/output file stream class (class)istringstreamInput string stream (class)ostringstreamOutput string stream (class)stringstreamInput/output string stream (class)streambufBase buffer class for streams (class)filebufFile stream buffer (class)stringbufString stream buffer (class) Objects: cinStandard input stream (object)coutStandard output stream (object)cerrStandard output stream for errors (object)clogStandard output stream for logging (object) Types: fposStream position class template (class template)streamoffStream offset type (type)streamposStream position type (type)streamsizeStream size type (type) Manipulators: boolalphaAlphanumerical bool values (function)decUse decimal base (function)endlInsert newline and flush (function)endsInsert null character (function)fixedUse fixed floating-point notation (function)flushFlush stream buffer (function)hexUse hexadecimal base (function)internalAdjust field by inserting characters at an internal position (function)leftAdjust output to the left (function)noboolalphaNo alphanumerical bool values (function)noshowbaseDo not show numerical base prefixes (function)noshowpointDo not show decimal point (function)noshowposDo not show positive signs (function)noskipwsDo not skip whitespaces (function)nounitbufDo not force flushes after insertions (function)nouppercaseDo not generate upper case letters (function)octUse octal base (function)resetiosflagsReset format flags (function)rightAdjust output to the right (function)scientificUse scientific floating-point notation (function)setbaseSet basefield flag (function)setfillSet fill character (function)setiosflagsSet format flags (function)setprecisionSet decimal precision (function)setwSet field width (function)showbaseShow numerical base prefixes (function)showpointShow decimal point (function)showposShow positive signs (function)skipwsSkip whitespaces (function)unitbufFlush buffer after insertions (function)uppercaseGenerate upper-case letters (function)wsExtract whitespaces (function) Home page | Privacy policy© cplusplus.com, 2000-2023 - All rights reserved - v3.3.4s Spotted an error? contact us 28.1 — Input and output (I/O) streams – Learn C++Navigate28.2 — Input with istreamTable of contents27.x — Chapter 27 summary and quizSite IndexLatest ChangesAboutSite FAQLeave feedbackReport an issueContact / SupportDonate SearchSearch for: SearchLearn C++Skill up with our free tutorialsSkip to contentNavigate28.2 — Input with istreamTable of contents27.x — Chapter 27 summary and quizSite IndexLatest ChangesAboutSite FAQLeave feedbackReport an issueContact / SupportDonate SearchSearch for: Search28.1 — Input and output (I/O) streamsAlex February 28, 2008, 4:10 pm September 11, 2023Input and output functionality is not defined as part of the core C++ language, but rather is provided through the C++ standard library (and thus resides in the std namespace). In previous lessons, you included the iostream library header and made use of the cin and cout objects to do simple I/O. In this lesson, we’ll take a look at the iostream library in more detail.The iostream libraryWhen you include the iostream header, you gain access to a whole hierarchy of classes responsible for providing I/O functionality (including one class that is actually named iostream). You can find a class hierarchy diagram for the non-file-I/O classes here.The first thing you may notice about this hierarchy is that it uses multiple inheritance (that thing we told you to avoid if at all possible). However, the iostream library has been designed and extensively tested in order to avoid any of the typical multiple inheritance problems, so you can use it freely without worrying.StreamsThe second thing you may notice is that the word “stream” is used an awful lot. At its most basic, I/O in C++ is implemented with streams. Abstractly, a stream is just a sequence of bytes that can be accessed sequentially. Over time, a stream may produce or consume potentially unlimited amounts of data.Typically we deal with two different types of streams. Input streams are used to hold input from a data producer, such as a keyboard, a file, or a network. For example, the user may press a key on the keyboard while the program is currently not expecting any input. Rather than ignore the users keypress, the data is put into an input stream, where it will wait until the program is ready for it.Conversely, output streams are used to hold output for a particular data consumer, such as a monitor, a file, or a printer. When writing data to an output device, the device may not be ready to accept that data yet -- for example, the printer may still be warming up when the program writes data to its output stream. The data will sit in the output stream until the printer begins consuming it.Some devices, such as files and networks, are capable of being both input and output sources.The nice thing about streams is the programmer only has to learn how to interact with the streams in order to read and write data to many different kinds of devices. The details about how the stream interfaces with the actual devices they are hooked up to is left up to the environment or operating system.Input/output in C++ios is a typedef for std::basic_ios Name* Email*Your email address will not be displayedFind a mistake? Leave a comment above!Correction-related comments will be deleted after processing to help reduce clutter. Thanks for helping to make the site better for everyone!Avatars from https://gravatar.com/ are connected to your provided email address.Notify me about replies: Label Name* Email*Your email address will not be displayedFind a mistake? Leave a comment above!Correction-related comments will be deleted after processing to help reduce clutter. Thanks for helping to make the site better for everyone!Avatars from https://gravatar.com/ are connected to your provided email address. 141 CommentsNewest Oldest Most VotedInline FeedbacksView all comments Load More Comments©2022 Learn C++wpDiscuzInsertYou are going to send email to SendMove CommentM std::basic_iostream - cppreference.com cppreference.com Log in Namespaces Page Discussion Variants Views View Edit History Actions std::basic_iostream From cppreference.com < cpp | io C++ Compiler support Freestanding and hosted Language Standard library Standard library headers Named requirements Feature test macros (C++20) Language support library Concepts library (C++20) Metaprogramming library (C++11) Diagnostics library General utilities library Strings library Containers library Iterators library Ranges library (C++20) Algorithms library Numerics library Localizations library Input/output library Filesystem library (C++17) Regular expressions library (C++11) Concurrency support library (C++11) Technical specifications Symbols index External libraries [edit] Input/output library I/O manipulators Print functions (C++23) C-style I/O Buffers basic_streambuf basic_filebuf basic_stringbuf basic_spanbuf(C++23) strstreambuf(deprecated in C++98) basic_syncbuf(C++20) Streams Abstractions ios_base basic_ios basic_istream basic_ostream basic_iostream File I/O basic_ifstream basic_ofstream basic_fstream String I/O basic_istringstream basic_ostringstream basic_stringstream Array I/O basic_ispanstream(C++23) basic_ospanstream(C++23) basic_spanstream(C++23) istrstream(deprecated in C++98) ostrstream(deprecated in C++98) strstream(deprecated in C++98) Synchronized Output basic_osyncstream(C++20) Types streamoff streamsize fpos Error category interface iostream_category(C++11) io_errc(C++11) [edit] std::basic_iostream Member functions basic_iostream::basic_iostream basic_iostream::~basic_iostream Protected member functions basic_iostream::operator= basic_iostream::swap [edit] Defined in header template< class CharT, class Traits = std::char_traits > class basic_iostream : public basic_istream public basic_ostream The class template basic_iostream provides support for high level input/output operations on streams. The supported operations include sequential reading or writing and formatting. This functionality is implemented over the interface provided by the std::basic_streambuf class. It is accessed through std::basic_ios class. Inheritance diagram Several typedefs for common character types are provided: Defined in header Type Definition std::iostream std::basic_iostream std::wiostream std::basic_iostream Contents 1 Member types 2 Member functions 3 Protected member functions 4 Inherited from std::basic_istream 4.1 Member functions 4.1.1 Formatted input 4.1.2 Unformatted input 4.1.3 Positioning 4.1.4 Miscellaneous 4.2 Member classes 5 Inherited from std::basic_ostream 5.1 Member functions 5.1.1 Formatted output 5.1.2 Unformatted output 5.1.3 Positioning 5.1.4 Miscellaneous 5.2 Member classes 6 Inherited from std::basic_ios 6.1 Member types 6.2 Member functions 6.2.1 State functions 6.2.2 Formatting 6.2.3 Miscellaneous 7 Inherited from std::ios_base 7.1 Member functions 7.1.1 Formatting 7.1.2 Locales 7.1.3 Internal extensible array 7.1.4 Miscellaneous 7.1.5 Member classes 7.2 Member types and constants 7.3 Defect reports 7.4 See also [edit] Member types Member type Definition char_type CharT[edit] traits_type Traits; the program is ill-formed if Traits::char_type is not CharT.[edit] int_type Traits::int_type[edit] pos_type Traits::pos_type[edit] off_type Traits::off_type[edit] [edit] Member functions (constructor) constructs the object (public member function) [edit] (destructor)[virtual] destructs the object (virtual public member function) [edit] [edit] Protected member functions operator=(C++11) move-assigns another basic_iostream (protected member function) [edit] swap(C++11) exchanges the state with another basic_iostream (public member function) [edit] Inherited from std::basic_istream Member functions Formatted input operator>> extracts formatted data (public member function of std::basic_istream Unformatted input get extracts characters (public member function of std::basic_istream peek reads the next character without extracting it (public member function of std::basic_istream unget unextracts a character (public member function of std::basic_istream putback puts a character into input stream (public member function of std::basic_istream getline extracts characters until the given character is found (public member function of std::basic_istream ignore extracts and discards characters until the given character is found (public member function of std::basic_istream read extracts blocks of characters (public member function of std::basic_istream readsome extracts already available blocks of characters (public member function of std::basic_istream gcount returns number of characters extracted by last unformatted input operation (public member function of std::basic_istream Positioning tellg returns the input position indicator (public member function of std::basic_istream seekg sets the input position indicator (public member function of std::basic_istream Miscellaneous sync synchronizes with the underlying storage device (public member function of std::basic_istream Member classes sentry implements basic logic for preparation of the stream for input operations (public member class of std::basic_istream Inherited from std::basic_ostream Member functions Formatted output operator<< inserts formatted data (public member function of std::basic_ostream Unformatted output put inserts a character (public member function of std::basic_ostream write inserts blocks of characters (public member function of std::basic_ostream Positioning tellp returns the output position indicator (public member function of std::basic_ostream seekp sets the output position indicator (public member function of std::basic_ostream Miscellaneous flush synchronizes with the underlying storage device (public member function of std::basic_ostream Member classes sentry implements basic logic for preparation of the stream for output operations (public member class of std::basic_ostream Inherited from std::basic_ios Member types Member type Definition char_type CharT traits_type Traits int_type Traits::int_type pos_type Traits::pos_type off_type Traits::off_type Member functions State functions good checks if no error has occurred i.e. I/O operations are available (public member function of std::basic_ios eof checks if end-of-file has been reached (public member function of std::basic_ios fail checks if an error has occurred (public member function of std::basic_ios bad checks if a non-recoverable error has occurred (public member function of std::basic_ios operator! checks if an error has occurred (synonym of fail()) (public member function of std::basic_ios operator bool checks if no error has occurred (synonym of !fail()) (public member function of std::basic_ios rdstate returns state flags (public member function of std::basic_ios setstate sets state flags (public member function of std::basic_ios clear modifies state flags (public member function of std::basic_ios Formatting copyfmt copies formatting information (public member function of std::basic_ios fill manages the fill character (public member function of std::basic_ios Miscellaneous exceptions manages exception mask (public member function of std::basic_ios imbue sets the locale (public member function of std::basic_ios rdbuf manages associated stream buffer (public member function of std::basic_ios tie manages tied stream (public member function of std::basic_ios narrow narrows characters (public member function of std::basic_ios widen widens characters (public member function of std::basic_ios Inherited from std::ios_base Member functions Formatting flags manages format flags (public member function of std::ios_base) [edit] setf sets specific format flag (public member function of std::ios_base) [edit] unsetf clears specific format flag (public member function of std::ios_base) [edit] precision manages decimal precision of floating point operations (public member function of std::ios_base) [edit] width manages field width (public member function of std::ios_base) [edit] Locales imbue sets locale (public member function of std::ios_base) [edit] getloc returns current locale (public member function of std::ios_base) [edit] Internal extensible array xalloc[static] returns a program-wide unique integer that is safe to use as index to pword() and iword() (public static member function of std::ios_base) [edit] iword resizes the private storage if necessary and access to the long element at the given index (public member function of std::ios_base) [edit] pword resizes the private storage if necessary and access to the void* element at the given index (public member function of std::ios_base) [edit] Miscellaneous register_callback registers event callback function (public member function of std::ios_base) [edit] sync_with_stdio[static] sets whether C++ and C I/O libraries are interoperable (public static member function of std::ios_base) [edit] Member classes failure stream exception (public member class of std::ios_base) [edit] Init initializes standard stream objects (public member class of std::ios_base) [edit] Member types and constants Type Explanation openmode stream open mode type The following constants are also defined: Constant Explanation[edit] app seek to the end of stream before each write[edit] binary open in binary mode[edit] in open for reading[edit] out open for writing[edit] trunc discard the contents of the stream when opening[edit] ate seek to the end of stream immediately after open[edit] noreplace (C++23) open in exclusive mode[edit] (typedef) [edit] fmtflags formatting flags type The following constants are also defined: Constant Explanation[edit] dec use decimal base for integer I/O: see std::dec[edit] oct use octal base for integer I/O: see std::oct[edit] hex use hexadecimal base for integer I/O: see std::hex[edit] basefield dec | oct | hex. Useful for masking operations[edit] left left adjustment (adds fill characters to the right): see std::left[edit] right right adjustment (adds fill characters to the left): see std::right[edit] internal internal adjustment (adds fill characters to the internal designated point): see std::internal[edit] adjustfield left | right | internal. Useful for masking operations[edit] scientific generate floating point types using scientific notation, or hex notation if combined with fixed: see std::scientific[edit] fixed generate floating point types using fixed notation, or hex notation if combined with scientific: see std::fixed[edit] floatfield scientific | fixed. Useful for masking operations[edit] boolalpha insert and extract bool type in alphanumeric format: see std::boolalpha[edit] showbase generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see std::showbase[edit] showpoint generate a decimal-point character unconditionally for floating-point number output: see std::showpoint[edit] showpos generate a + character for non-negative numeric output: see std::showpos[edit] skipws skip leading whitespace before certain input operations: see std::skipws[edit] unitbuf flush the output after each output operation: see std::unitbuf[edit] uppercase replace certain lowercase letters with their uppercaseequivalents in certain output operations: see std::uppercase[edit] (typedef) [edit] iostate state of the stream type The following constants are also defined: Constant Explanation[edit] goodbit no error[edit] badbit irrecoverable stream error[edit] failbit input/output operation failed (formatting or extraction error)[edit] eofbit associated input sequence has reached end-of-file[edit] (typedef) [edit] seekdir seeking direction type The following constants are also defined: Constant Explanation[edit] beg the beginning of a stream[edit] end the ending of a stream[edit] cur the current position of stream position indicator[edit] (typedef) [edit] event specifies event type (enum) [edit] event_callback callback function type (typedef) [edit] [edit] Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. DR Applied to Behavior as published Correct behavior LWG 271 C++98 the member types char_type, traits_type, int_type, pos_type and off_type were not defined(std::basic_istream and std::basic_ostream both define these types, resulted in ambiguity) definethese types [edit] See also Input/output manipulators Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_iostream&oldid=165143" Navigation Support usRecent changesFAQOffline version Toolbox What links hereRelated changesUpload fileSpecial pagesPrintable versionPermanent linkPage information In other languages DeutschEspañolFrançaisItaliano日本語PortuguêsРусский中文 This page was last modified on 7 December 2023, at 00:38. This page has been accessed 236,816 times. Privacy policy About cppreference.com Disclaimers Input/output (C++) - Wikipedia
Standard library header
1.5 — Introduction to iostream: cout, cin, and endl – Learn C++
| Microsoft Learn
C++ iostream
28.1 — Input and output (I/O) streams – Learn C++
std::basic_iostream - cppreference.com