?? ch16.htm
字號:
<P>At times you want to ignore the remaining characters on a line until you hit either
end of line (EOL) or end of file (EOF). The member function <TT>ignore()</TT> serves
this purpose. <TT>ignore()</TT> takes two parameters, the maximum number of characters
to ignore and the termination character. If you write <TT>ignore(80,'\n')</TT>, up
to 80 characters will be thrown away until a newline character is found. The newline
is then thrown away and the <TT>ignore()</TT> statement ends. Listing 16.8 illustrates
the use of <TT>ignore()</TT>.</P>
<P><A NAME="Heading33"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.8. Using
ignore().</B></FONT></P>
<PRE><FONT COLOR="#0066FF">1: // Listing 16.8 - Using ignore()
2: #include <iostream.h>
3:
4: int main()
5: {
6: char stringOne[255];
7: char stringTwo[255];
8:
9: cout << "Enter string one:";
10: cin.get(stringOne,255);
11: cout << "String one" << stringOne << endl;
12:
13: cout << "Enter string two: ";
14: cin.getline(stringTwo,255);
15: cout << "String two: " << stringTwo << endl;
16:
17: cout << "\n\nNow try again...\n";
18:
19: cout << "Enter string one: ";
20: cin.get(stringOne,255);
21: cout << "String one: " << stringOne<< endl;
22:
23: cin.ignore(255,'\n');
24:
25: cout << "Enter string two: ";
26: cin.getline(stringTwo,255);
27: cout << "String Two: " << stringTwo<< endl;
28: return 0;
<TT>29: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: Enter string one:once upon a time
String oneonce upon a time
Enter string two: String two:
Now try again...
Enter string one: once upon a time
String one: once upon a time
Enter string two: there was a
String Two: there was a</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis</B></FONT><FONT COLOR="#000000"><B>: </B></FONT>On
lines 6 and 7, two character arrays are created. On line 9, the user is prompted
for 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 terminates
on 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 14
reads the newline that is already in the buffer and terminates immediately, before
the 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" the
newline 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 rather
handy: <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.9
illustrates how these might be used.</P>
<P><A NAME="Heading35"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.9. Using
peek() 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: else
13: 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>On
line 6, a character variable, <TT>ch</TT>, is declared, and on line 7, the user is
prompted to enter a phrase. The purpose of this program is to turn any exclamation
marks (<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 current
character is an exclamation point, it is thrown away and the <TT>$</TT> symbol is
put back into the input buffer; it will be read the next time through. If the current
item 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't
find a pound symbol if it is the first character), but it does illustrate how these
methods work. They are relatively obscure, so don't spend a lot of time worrying
about when you might really use them. Put them into your bag of tricks; they'll come
in 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 possible
to format the data, aligning columns and writing the numeric data in decimal and
hexadecimal. 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 data
it is buffering. You can call the <TT>flush()</TT> method directly, either by calling
the <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 emptied
and 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 output
device. 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> just
as 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. Using
put().</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 process
repeats, each letter being written and the <TT>cout</TT> object returned until the
final 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 characters
to write. Listing 16.11 illustrates its use.</P>
<P><A NAME="Heading40"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.11. Using
write().</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 land
One if by
One 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>On
line 7, one phrase is created. On line 11, the integer <TT>fullLength</TT> is set
to 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 length
is 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 the
full 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 instructed
to write an extra six characters. Once the phrase is written, the next six bytes
of 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 (decimal
or hexadecimal) to use, how wide to make the fields, and what character to use to
fill in fields. A state flag is just a byte whose individual bits are each assigned
a 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 immediately
reverts to the default. Listing 16.12 illustrates its use.</P>
<P><A NAME="Heading43"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 16.12. Adjusting
the width of output.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">1: // Listing 16.12 - Adjusting the width of output
2: #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< End
Start > 123< Next >456< End
Start >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 width
is 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 width
is set to 25, and then prints the value 456. Note that 456 is printed in a field
whose width is reset to just large enough; as stated, the effect of <TT>width()</TT>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -