Sams Teach Yourself C++ in 21 Days

(singke) #1
Line 6 is evaluated like this:std::cout.put(‘H’)writes the letter “H” to the
screen and returns a coutobject. This leaves the following:
cout.put(‘e’).put(‘l’).put(‘l’).put(‘o’).put(‘\n’);
The letter “e” is written, and, again, a coutobject is returned leaving:
cout.put(‘l’).put(‘l’).put(‘o’).put(‘\n’);
This process repeats, each letter being written and the coutobject returned until the final
character (‘\n’) is written and the function returns.

Writing More with write()
The functionwrite()works the same as the insertion operator (<<), except that it takes a
parameter that tells the function the maximum number of characters to write:
cout.write(Text, Size)
As you can see, the first parameter for write()is the text that will be printed. The sec-
ond parameter,Size, is the number of characters that will be printed from Text. Note
that this number might be smaller or larger than the actual size of the Text. If it is larger,
you will output the values that reside in memory after the Textvalue. Listing 17.11 illus-
trates its use.

LISTING17.11 Using write()
0: // Listing 17.11 - Using write()
1: #include <iostream>
2: #include <string.h>
3: using namespace std;
4:
5: int main()
6: {
7: char One[] = “One if by land”;
8:
9: int fullLength = strlen(One);
10: int tooShort = fullLength -4;
11: int tooLong = fullLength + 6;
12:
13: cout.write(One,fullLength) << endl;
14: cout.write(One,tooShort) << endl;
15: cout.write(One,tooLong) << endl;
16: return 0;
17: }

614 Day 17


Some nonstandard compilers have trouble printing using this code. If your
compiler does not print the word Hello, you might want to skip this listing.

NOTE

ANALYSIS
Free download pdf