📄 ch16.htm
字号:
Now try again...Enter string one: once upon a timeString one: once upon a timeEnter string two: there was aString Two: there was a</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis</B></FONT><FONT COLOR="#000000"><B>: </B></FONT>Onlines 6 and 7, two character arrays are created. On line 9, the user is promptedfor input and types <TT>once upon a time</TT>, followed by Enter. On line 10, <TT>get()</TT>is used to read this string. <TT>get()</TT> fills <TT>stringOne</TT> and terminateson the newline, but leaves the newline character in the input buffer.</P><P>On line 13, the user is prompted again, but the <TT>getline()</TT> on line 14reads the newline that is already in the buffer and terminates immediately, beforethe user can enter any input.</P><P>On line 19, the user is prompted again and puts in the same first line of input.This time, however, on line 23, <TT>ignore()</TT> is used to "eat" thenewline character. Thus, when the <TT>getline()</TT> call on line 26 is reached,the input buffer is empty, and the user can input the next line of the story.<H4 ALIGN="CENTER"><A NAME="Heading34"></A><FONT COLOR="#000077">peek() and putback()</FONT></H4><P>The input object <TT>cin</TT> has two additional methods that can come in ratherhandy: <TT>peek()</TT>, which looks at but does not extract the next character, and<TT>putback()</TT>, which inserts a character into the input stream. Listing 16.9illustrates how these might be used.</P><P><A NAME="Heading35"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.9. Usingpeek() and putback().</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 16.9 - Using peek() and putback()2: #include <iostream.h>3:4: int main()5: {6: char ch;7: cout << "enter a phrase: ";8: while ( cin.get(ch) )9: {10: if (ch == `!')11: cin.putback(`$');12: else13: cout << ch;14: while (cin.peek() == `#')15: cin.ignore(1,'#');16: }17: return 0;<TT>18: }</TT></FONT><FONT COLOR="#0066FF">Output: enter a phrase: Now!is#the!time#for!fun#!Now$isthe$timefor$fun$</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis</B></FONT><FONT COLOR="#000000"><B>: </B></FONT>Online 6, a character variable, <TT>ch</TT>, is declared, and on line 7, the user isprompted to enter a phrase. The purpose of this program is to turn any exclamationmarks (<TT>!</TT>) into dollar signs (<TT>$</TT>) and to remove any pound symbols(<TT>#</TT>).</P><P>The program loops as long as it is getting characters other than the end of file(remember that <TT>cin.get()</TT> returns <TT>0</TT> for end of file). If the currentcharacter is an exclamation point, it is thrown away and the <TT>$</TT> symbol isput back into the input buffer; it will be read the next time through. If the currentitem is not an exclamation point, it is printed. The next character is "peeked"at, and when pound symbols are found, they are removed.</P><P>This is not the most efficient way to do either of these things (and it won'tfind a pound symbol if it is the first character), but it does illustrate how thesemethods work. They are relatively obscure, so don't spend a lot of time worryingabout when you might really use them. Put them into your bag of tricks; they'll comein handy sooner or later.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><TT><B>TIP:</B></TT></FONT><TT><B> </B>peek()</TT> and <TT>putback()</TT> are typically used for parsing strings and other data, such as when writing a compiler. <HR></BLOCKQUOTE><H3 ALIGN="CENTER"><A NAME="Heading36"></A><FONT COLOR="#000077">Output with cout</FONT></H3><P>You have used <TT>cout</TT> along with the overloaded insertion operator (<TT><<</TT>)to write strings, integers, and other numeric data to the screen. It is also possibleto format the data, aligning columns and writing the numeric data in decimal andhexadecimal. This section will show you how.<H4 ALIGN="CENTER"><A NAME="Heading37"></A><FONT COLOR="#000077">Flushing the Output</FONT></H4><P>You've already seen that using <TT>endl</TT> will flush the output buffer. <TT>endl</TT>calls <TT>cout</TT>'s member function <TT>flush()</TT>, which writes all of the datait is buffering. You can call the <TT>flush()</TT> method directly, either by callingthe <TT>flush()</TT> member method or by writing the following:</P><PRE><FONT COLOR="#0066FF">cout << flush</FONT></PRE><P>This can be convenient when you need to ensure that the output buffer is emptiedand that the contents are written to the screen.<H3 ALIGN="CENTER"><A NAME="Heading38"></A><FONT COLOR="#000077">Related Functions</FONT></H3><P>Just as the extraction operator can be supplemented with <TT>get()</TT> and <TT>getline()</TT>,the insertion operator can be supplemented with <TT>put()</TT> and <TT>write()</TT>.</P><P>The function <TT>put()</TT> is used to write a single character to the outputdevice. Because <TT>put()</TT> returns an <TT>ostream</TT> reference, and because<TT>cout</TT> is an <TT>ostream</TT> object, you can concatenate <TT>put()</TT> justas you do the insertion operator. Listing 16.10 illustrates this idea.</P><P><A NAME="Heading39"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.10. Usingput().</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 16.10 - Using put()2: #include <iostream.h>3:4: int main()5: {6: cout.put(`H').put(`e').put(`l').put(`l').put(`o').put(`\n');7: return 0;<TT>8: }</TT>Output: Hello</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis</B></FONT><FONT COLOR="#000000"><B>:</B></FONT><B></B>Line 6 is evaluated like this: <TT>cout.put(`H')</TT> writes the letter <TT>H</TT>to the screen and returns the <TT>cout</TT> object. This leaves the following:</P><PRE><FONT COLOR="#0066FF">cout.put(`e').put(`l').put(`l').put(`o').put(`\n');</FONT></PRE><P>The letter <TT>e</TT> is written, leaving <TT>cout.put(`l')</TT>. This processrepeats, each letter being written and the <TT>cout</TT> object returned until thefinal character (<TT>`\n'</TT>) is written and the function returns.</P><P>The function <TT>write()</TT> works just like the insertion operator (<TT><<</TT>),except that it takes a parameter that tells the function the maximum number of charactersto write. Listing 16.11 illustrates its use.</P><P><A NAME="Heading40"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.11. Usingwrite().</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 16.11 - Using write()2: #include <iostream.h>3: #include <string.h>4:5: int main()6: {7: char One[] = "One if by land";8:9:10:11: int fullLength = strlen(One);12: int tooShort = fullLength -4;13: int tooLong = fullLength + 6;14:15: cout.write(One,fullLength) << "\n";16: cout.write(One,tooShort) << "\n";17: cout.write(One,tooLong) << "\n";18: return 0;<TT>19: }</TT></FONT><FONT COLOR="#0066FF">Output: One if by landOne if byOne if by land i?!</FONT></PRE><BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>The last line of output may look different on your computer. <HR></BLOCKQUOTE><P><FONT COLOR="#000077"><B>Analysis</B></FONT><FONT COLOR="#000000"><B>: </B></FONT>Online 7, one phrase is created. On line 11, the integer <TT>fullLength</TT> is setto the length of the phrase and <TT>tooShort</TT> is set to that length minus four,while <TT>tooLong</TT> is set to <TT>fullLength</TT> plus six.</P><P>On line 15, the complete phrase is printed using <TT>write()</TT>. The lengthis set to the actual length of the phrase, and the correct phrase is printed.</P><P>On line 16, the phrase is printed again, but is four characters shorter than thefull phrase, and that is reflected in the output.</P><P>On line 17, the phrase is printed again, but this time <TT>write()</TT> is instructedto write an extra six characters. Once the phrase is written, the next six bytesof contiguous memory are written.<H3 ALIGN="CENTER"><A NAME="Heading41"></A><FONT COLOR="#000077">Manipulators, Flags,and Formatting Instructions</FONT></H3><P>The output stream maintains a number of state flags, determining which base (decimalor hexadecimal) to use, how wide to make the fields, and what character to use tofill in fields. A state flag is just a byte whose individual bits are each assigneda special meaning. Manipulating bits in this way is discussed on Day 21. Each of<TT>ostream</TT>'s flags can be set using member functions and manipulators.<H4 ALIGN="CENTER"><A NAME="Heading42"></A><FONT COLOR="#000077">Using cout.width()</FONT></H4><P>The default width of your output will be just enough space to print the number,character, or string in the output buffer. You can change this by using <TT>width()</TT>.Because <TT>width()</TT> is a member function, it must be invoked with a <TT>cout</TT>object. It only changes the width of the very next output field and then immediatelyreverts to the default. Listing 16.12 illustrates its use.</P><P><A NAME="Heading43"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.12. Adjustingthe width of output.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 16.12 - Adjusting the width of output2: #include <iostream.h>3:4: int main()5: {6: cout << "Start >";7: cout.width(25);8: cout << 123 << "< End\n";9:10: cout << "Start >";11: cout.width(25);12: cout << 123<< "< Next >";13: cout << 456 << "< End\n";14:15: cout << "Start >";16: cout.width(4);17: cout << 123456 << "< End\n";18:19: return 0;<TT>20: }</TT></FONT><FONT COLOR="#0066FF">Output: Start > 123< EndStart > 123< Next >456< EndStart >123456< End</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis</B></FONT><FONT COLOR="#000000"><B>:</B></FONT><B></B>The first output, on lines 6-8, prints the number 123 within a field whose widthis set to 25 on line 7. This is reflected in the first line of output.</P><P>The second line of output first prints the value 123 in the same field whose widthis set to 25, and then prints the value 456. Note that 456 is printed in a fieldwhose width is reset to just large enough; as stated, the effect of <TT>width()</TT>lasts only as long as the very next output.</P><P>The final output reflects that setting a width that is smaller than the outputis exactly like setting a width that is just large enough.<H4 ALIGN="CENTER"><A NAME="Heading44"></A><FONT COLOR="#000077">Setting the FillCharacters</FONT></H4><P>Normally <TT>cout</TT> fills the empty field created by a call to <TT>width()</TT>with spaces, as shown above. At times you may want to fill the area with other characters,such as asterisks. To do this, you call <TT>fill()</TT> and pass in as a parameterthe character you want used as a fill character. Listing 16.13 illustrates this.</P><P><A NAME="Heading45"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.13. Usingfill().</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 16.3 - fill()2:3: #include <iostream.h>4:5: int main()6: {7: cout << "Start >";8: cout.width(25);9: cout << 123 << "< End\n";10:11:12: cout << "Start >";13: cout.width(25);14: cout.fill(`*');15: cout << 123 << "< End\n";16: return 0;<TT>17: }</TT></FONT><FONT COLOR="#0066FF">Output: Start > 123< EndStart >******************123< End</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis</B></FONT><FONT COLOR="#000000"><B>:</B></FONT><B></B>Lines 7-9 repeat the functionality from the previous example. Lines 12-15 repeatthis again, but this time, on line 14, the fill character is set to asterisks, asreflected in the output.<H4 ALIGN="CENTER"><A NAME="Heading47"></A><FONT COLOR="#000077">Set Flags</FONT></H4><P>The <TT>iostream</TT> objects keep track of their state by using flags. You canset these flags by calling <TT>setf()</TT> and passing in one or another of the predefinedenumerated constants.</P><DL> <DD><HR><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>Objects are said to have <I>state </I>when some or all of their data represents a condition that can change during the course of the program. <HR></DL><P>For example, you can set whether or not to show trailing zeros (so that 20.00does not become truncated to 20). To turn trailing zeros on, call <TT>setf(ios::showpoint)</TT>.</P><P>The enumerated constants are scoped to the <TT>iostream</TT> class (<TT>ios</TT>)and thus are called with the full qualification <TT>ios::flagname</TT>, such as <TT>ios::showpoint</TT>.</P><P>You can turn on the plus sign (<TT>+</TT>) before positive numbers by using <TT>ios::showpos</TT>.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -