📄 for_5394.htm
字号:
<HTML><HEAD><TITLE>2.3 Formatted Input/Output</TITLE></HEAD><BODY><A HREF="ug2.htm"><IMG SRC="images/banner.gif"></A><BR><A HREF="arc_7049.htm"><IMG SRC="images/prev.gif"></A><A HREF="booktoc2.htm"><IMG SRC="images/toc.gif"></A><A HREF="err_7848.htm"><IMG SRC="images/next.gif"></A><BR><STRONG>Click on the banner to return to the user guide home page.</STRONG><H2>2.3 Formatted Input/Output</H2><P>This section describes the formatting facilities of iostreams. Here we begin using the predefined streams, and see how to do simple input and output. We then explore in detail how to control parsing and formatting.</P><A NAME="2.3.1"><H3>2.3.1 The Predefined Streams</H3></A><P>There are eight predefined standard streams that are automatically created and initialized at program start. These standard streams are associated with the C standard files <SAMP>stdin</SAMP>, <SAMP>stdout</SAMP>, and <SAMP>stderr</SAMP>, as shown in Table 1:</P><H4>Table 1: Predefined standard streams with their associated C standard files</H4><CENTER><TABLE BORDER CELLSPACING=3 CELLPADDING=3><TR VALIGN=top><TD>Narrow character stream<BR></TD><TD>Wide character stream<BR></TD><TD>Associated C standard files<BR></TD></TR><TR VALIGN=top><TD><SAMP>cin</SAMP><BR></TD><TD><SAMP>wcin</SAMP><BR></TD><TD><SAMP>stdin</SAMP><BR></TD></TR><TR VALIGN=top><TD><SAMP>cout</SAMP><BR></TD><TD><SAMP>wcout</SAMP><BR></TD><TD><SAMP>stdout</SAMP><BR></TD></TR><TR VALIGN=top><TD><SAMP>cerr</SAMP><BR></TD><TD><SAMP>wcerr</SAMP><BR></TD><TD><SAMP>stderr</SAMP><BR></TD></TR><TR VALIGN=top><TD><SAMP>clog</SAMP><BR></TD><TD><SAMP>wclog</SAMP><BR></TD><TD><SAMP>stderr</SAMP><BR></TD></TR></TABLE></CENTER><P>Like the C standard files, these streams are all associated by default with the terminal.</P><P>The difference between <SAMP>clog</SAMP> and <SAMP>cerr</SAMP> is that <SAMP>clog</SAMP> is fully buffered, whereas output to <SAMP>cerr</SAMP> is written to the external device after each formatting. With a fully buffered stream, output to the actual external device is written only when the buffer is full. Thus <SAMP>clog</SAMP> is more efficient for redirecting output to a file, while <SAMP>cerr</SAMP> is mainly useful for terminal I/O. Writing to the external device after every formatting, to the terminal in the case of <SAMP>cerr</SAMP>, serves the purpose of synchronizing output to and input from the terminal.</P><P>The standard streams are initialized in such a way that they can be used in constructors and destructors of static objects. Also, the predefined streams are synchronized with their associated C standard files. See <A HREF="syn_4687.htm#2.10.5">Section 2.10.5</A> for details.</P><A NAME="2.3.2"><H3>2.3.2 Input and Output Operators</H3></A><P>Now let's try to do some simple input and output to the predefined streams. The iostreams facility defines shift operators for formatted stream input and output. The output operator is the shift operator <SAMP>operator<<()</SAMP>, also called the <I>inserter </I>(defined in <A HREF="arc_7049.htm#2.2.4.1">Section 2.2.4.1</A>)<I>:</I></P><PRE>cout << "result: " << x << '\n';</PRE><P>Input is done through another shift operator <SAMP>operator>>()</SAMP>, often referred to as the <I>extractor</I> (also defined in <A HREF="arc_7049.htm#2.2.4.1">Section 2.2.4.1</A>):</P><PRE>cin >> x >> y;</PRE><P>Both operators are overloaded for all built-in types in C++, as well as for some of the types defined in the Standard C++ Library; for example, there are inserters and extractors for <SAMP>bool</SAMP>, <SAMP>char</SAMP>, <SAMP>int</SAMP>, <SAMP>long</SAMP>, <SAMP>float</SAMP>, <SAMP>double</SAMP>, <SAMP>string</SAMP>, etc. When you insert or extract a value to or from a stream, the C++ function overload resolution chooses the correct extractor operator, based on the value's type. This is what makes C++ iostreams type-safe and better than C stdio (see <A HREF="arc_7049.htm#2.2.1.1">Section 2.2.1.1</A>).</P><P>It is possible to print several units in one expression. For example:</P><PRE>cout << "result: " << x;</PRE><P>is equivalent to:</P><PRE>(cout.operator<<("result: ")).operator<<(x);</PRE><P>This is possible because each shift operator returns a reference to the respective stream. Almost all shift operators for built-in types are member functions of their respective stream class.<A HREF="endnote2.htm#fn15">[15]</A> They are defined according to the following patterns:</P><PRE>template<class charT, class traits>basic_istream<charT, traits>& basic_istream<charT, traits>::operator>>(type& x){ // read x return *this;}</PRE><P>and: </P><PRE>template<class charT, class traits>basic_ostream<charT, traits>&basic_ostream<charT, traits>::operator<<(type x){ // write x return *this;}</PRE><P>Simple input and output of units as shown above is useful, yet not sufficient in many cases. For example, you may want to vary the way output is formatted, or input is parsed. Iostreams allow you to control the formatting features of its input and output operators in many ways. With iostreams, you can specify:</P><UL><LI><P>The width of an output field and the adjustment of the output within this field;</P></LI><LI><P>The precision and format of floating point numbers, and whether or not the decimal point should always be included;</P></LI><LI><P>Whether you want to skip white spaces when reading from an input stream;</P></LI><LI><P>Whether integral values are displayed in decimal, octal or hexadecimal format,</P></LI></UL><P>and many other formatting options. </P><P>There are two mechanisms that have an impact on formatting:</P><UL><LI><P>Formatting control through a stream's format state, and</P></LI><LI><P>Localization through a stream's locale.</P></LI></UL><P>The stream's format state is the main means of format control, as we will demonstrate in the next section.</P><A NAME="2.3.3"><H3>2.3.3 Format Control Using the Stream's Format State</H3></A><A NAME="2.3.3.1"><H4>2.3.3.1 Format Parameters</H4></A><P>Associated with each stream are a number of <I>format state variables </I>that control the details of formatting and parsing. Format state variables are classes inherited from a stream's base class, either <B><I><B><I>ios_base </I></B></B></I>or <B><I><B><I>basic_ios<charT,traits></I></B></B></I>. There are two kinds of format parameters:</P><UL><LI><P><B><I>Parameters that can have an arbitrary value.</I></B> The value is stored as a private data member in one of the base classes, and set and retrieved through public member functions inherited from that base class. There are three such parameters, described in Table 2 below:</P><CENTER><TABLE BORDER CELLSPACING=3 CELLPADDING=3><TR VALIGN=top><TD><B>Access function</B><BR></TD><TD><B>Defined in <BR><BR>base class</B></TD><TD><B>Effect</B><BR></TD><TD><B>Default</B><BR></TD></TR><TR VALIGN=top><TD><SAMP>width()</SAMP><BR></TD><TD><B><I><B><I>ios_base</I></B></B></I><BR></TD><TD>Minimal field width<BR></TD><TD>0<BR></TD></TR><TR VALIGN=top><TD><SAMP>precision()</SAMP><BR></TD><TD><B><I><B><I>ios_base</I></B></B></I><BR></TD><TD>Precision of floating point values<BR></TD><TD>6<BR></TD></TR><TR VALIGN=top><TD><SAMP>fill()</SAMP><BR></TD><TD><B><I><B><I>basic_ios</I></B></B></I><BR></TD><TD>Fill character for padding<BR></TD><TD>The space character<BR></TD></TR></TABLE></CENTER><BR></LI><LI><P><B><I>Parameters that can have only a few different values, typically two or three.</I></B> They are represented by one or more bits in a data member of type <SAMP>fmtflags</SAMP> in class <B><I><B><I>ios_base</I></B></B></I>. These are usually called <I>format flags</I>. You can set format flags using the <SAMP>setf()</SAMP> function in class <B><I><B><I>ios_base</I></B></B></I>, clear them using <SAMP>unsetf()</SAMP>, and retrieve them through the <SAMP>flags()</SAMP> function. </P><P>Some format flags are grouped because they are mutually exclusive; for example, output within an output field can be adjusted to the left or to the right, or to an internally specified adjustment. One and only one of the corresponding three format flags, <SAMP>left</SAMP>, <SAMP>right</SAMP>, or <SAMP>internal</SAMP>, can be set.<A HREF="endnote2.htm#fn16">[16]</A> If you want to set one of these bits to 1, you need to set the other two to 0. To make this easier, there are <I>bit groups</I> whose main function is to reset all bits in one group. The bit group for adjustment is <SAMP>adjustfield</SAMP>, defined as <SAMP>left | right | internal</SAMP>. </P></UL><P>Table 3 below gives an overview of all format flags and their effects on input and output operators. (For details on how the format flags affect input and output operations, see the <I>Class Reference</I> entry for <B><I><B><I>ios_base</I></B></B></I>.) The first column below<I>, format flag</I>, lists the flag names; for example, <SAMP>showpos</SAMP> stands for <SAMP>ios_base::showpos</SAMP>. The<I> group</I> column lists the name of the group for flags that are mutually exclusive. The third column gives a brief description of the effect of setting the flag. The <I>stdio</I> column refers to format characters used by the C functions <SAMP>scanf()</SAMP> or <SAMP>printf()</SAMP> that have the same or similar effect. The last column, <I>default</I>, lists the setting that is used if you do not explicitly set the flag.</P><H4>Table 3: Flags and their effects on operators</H4><CENTER><TABLE BORDER CELLSPACING=3 CELLPADDING=3><TR VALIGN=top><TD><B>Format flag</B><BR></TD><TD><B>Group</B><BR></TD><TD><B>Effect</B><BR></TD><TD><B>stdio </B><BR></TD><TD><B>Default</B><BR></TD></TR><TR VALIGN=top><TD> </TD><TD><SAMP>adjustfield</SAMP><BR></TD><TD>Adds fill characters to certain generated output for adjustment:<BR></TD><TD> </TD><TD><SAMP>left</SAMP><A HREF="endnote2.htm#fn17">[17]</A><BR></TD></TR><TR VALIGN=top><TD><SAMP>left</SAMP><BR><SAMP>right</SAMP><BR><SAMP>internal</SAMP><BR></TD><TD> </TD><TD>left<BR>right<BR>adds fill characters at designated internal point<BR></TD><TD><SAMP>-</SAMP><BR><SAMP>0</SAMP><BR></TD><TD> </TD></TR><TR><BR></TR><TR VALIGN=top><TD></TD><TD><SAMP>basefield</SAMP><BR></TD><TD>Converts integer input or generates integer output in:<BR></TD><TD><SAMP>%i</SAMP><BR></TD><TD><SAMP>dec</SAMP><BR></TD></TR><TR VALIGN=top><TD><SAMP>dec</SAMP><BR></TD><TD> </TD><TD>decimal base<BR></TD><TD><SAMP>%d,%u</SAMP><BR></TD><TD> </TD></TR><TR VALIGN=top><TD><SAMP>oct</SAMP><BR></TD><TD> </TD><TD>octal base<BR></TD><TD><SAMP>%o</SAMP><BR></TD><TD> </TD></TR><TR VALIGN=top><TD><SAMP>hex</SAMP><BR></TD><TD> </TD><TD>hexadecimal base<BR></TD><TD><SAMP>%x</SAMP><BR></TD><TD> </TD></TR><TR><BR></TR><TR VALIGN=top><TD></TD><TD><SAMP>floatfield</SAMP><BR></TD><TD>Generates floating point output:<BR></TD><TD><SAMP>%g,%G</SAMP><BR></TD><TD><SAMP>fixed</SAMP><BR></TD></TR><TR VALIGN=top><TD><SAMP>fixed</SAMP><BR></TD><TD> </TD><TD>in fixed-point notation<BR></TD><TD><SAMP>%f</SAMP><BR></TD><TD> </TD></TR><TR VALIGN=top><TD><SAMP>scientific</SAMP><BR></TD><TD> </TD><TD>in scientific notation<BR></TD><TD><SAMP>%e,%E</SAMP><BR></TD><TD> </TD></TR><TR><TD></TD></TR><TR VALIGN=top><TD><SAMP>boolalpha</SAMP><BR></TD><TD> </TD><TD>Inserts and extracts <SAMP>bool</SAMP> values in alphabetic format<BR></TD><TD> </TD><TD>0<BR></TD></TR>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -