Professional Documents
Culture Documents
Stream
Input/Output
Consciousness does not
appear to itself chopped up
in bits A river or a
stream are the metaphors
by which it is most naturally
described.
William James
OBJECTIVES
In this chapter you will learn:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-Review Exercises
15.1
c) Member function
ANS: flags.
ANS: <iostream>.
ANS: <iomanip>.
f) Header file
cessing.
and
must be included.
ANS: <fstream>.
ANS: write.
ANS: <<.
or the
.
.
l) The four objects that correspond to the standard devices on the system include
,
,
and
.
ANS: cin, cout, cerr and clog.
ANS: showpos.
15.2
State whether the following are true or false. If the answer is false, explain why.
a) The stream member function flags with a long argument sets the flags state variable
to its argument and returns its previous value.
ANS: False. The stream member function flags with a fmtflags argument sets the flags
state variable to its argument and returns the prior state settings.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-Review Exercises
b) The stream insertion operator << and the stream-extraction operator >> are overloaded
to handle all standard data typesincluding strings and memory addresses (stream-insertion only)and all user-defined data types.
ANS: False. The stream insertion and stream extraction operators are not overloaded for all
user-defined types. The programmer of a class must specifically provide the overloaded operator functions to overload the stream operators for use with each user-defined type.
c) The stream member function flags with no arguments resets the streams format state.
ANS: False. The stream member function flags with no arguments returns the current format settings as a fmtflags data type, which represents the format state.
d) The stream extraction operator >> can be overloaded with an operator function that
takes an istream reference and a reference to a user-defined type as arguments and returns an istream reference.
ANS: True.
e) The stream insertion operator << can be overloaded with an operator function that takes
an istream reference and a reference to a user-defined type as arguments and returns an
istream reference.
ANS: False. To overload the stream insertion operator <<, the overloaded operator function
must take an ostream reference and a reference to a user-defined type as arguments
and return an ostream reference.
f) Input with the stream extraction operator >> always skips leading white-space characters
in the input stream, by default.
ANS: True.
g) The stream member function rdstate returns the current state of the stream.
ANS: True.
h) The cout stream normally is connected to the display screen.
ANS: True.
i) The stream member function good returns true if the bad, fail and eof member functions all return false.
ANS: True.
j) The cin stream normally is connected to the display screen.
ANS: False. The cin stream is connected to the standard input of the computer, which normally is the keyboard.
k) If a nonrecoverable error occurs during a stream operation, the bad member function
will return true.
ANS: True.
l) Output to cerr is unbuffered and output to clog is buffered.
ANS: True.
m) Stream manipulator showpoint forces floating-point values to print with the default six
digits of precision unless the precision value has been changed, in which case floatingpoint values print with the specified precision.
ANS: True.
n) The ostream member function put outputs the specified number of characters.
ANS: False. The ostream member function put outputs its single-character argument.
o) The stream manipulators dec, oct and hex affect only the next integer output operation.
ANS: False. The stream manipulators dec, oct and hex set the output format state for integers to the specified base until the base is changed again or the program terminates.
p) By default, memory addresses are displayed as long integers.
ANS: False. Memory addresses are displayed in hexadecimal format by default. To display
addresses as long integers, the address must be cast to a long value.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4
15.3
b) Use a stream manipulator that causes the exponent in scientific notation and the letters
in hexadecimal values to print in capital letters.
ANS: cout << uppercase;
f) Use a stream manipulator such that, when integer values are output, the integer base for
octal and hexadecimal values is displayed.
ANS: cout << showbase;
h) Use a stream member function to set the fill character to '*' for printing in field widths
larger than the values being output. Write a separate statement to do this with a stream
manipulator.
ANS: cout.fill( '*' );
cout << setfill( '*' );
'O'
j) Get the value of the next character in the input stream without extracting it from the
stream.
ANS: cin.peek();
k) Input a single character into variable charValue of type char, using the istream member
function get in two different ways.
ANS: charValue = cin.get();
cin.get( charValue );
l) Input and discard the next six characters in the input stream.
ANS: cin.ignore( 6 );
m) Use istream member function read to input 50 characters into char array line.
ANS: cin.read( line, 50 );
n) Read 10 characters into character array name. Stop reading characters if the '.' delimiter
is encountered. Do not remove the delimiter from the input stream. Write another
statement that performs this task and removes the delimiter from the input.
ANS: cin.get( name, 10, '.' );
cin.getline( name, 10, '.' );
o) Use the istream member function gcount to determine the number of characters input
into character array line by the last call to istream member function read, and output
that number of characters, using ostream member function write.
ANS: cout.write( line, cin.gcount() );
p) Output the following values: 124, 18.376, 'Z', 1000000 and "String".
ANS: cout << 124 << ' ' << 18.376 << ' ' << "Z " << 1000000 << " String";
q) Print the current precision setting, using a member function of object cout.
ANS: cout << cout.precision();
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-Review Exercises
r) Input an integer value into int variable
variable percentageRate.
months
s) Print 1.92, 1.925 and 1.9258 separated by tabs and with 3 digits of precision, using a
manipulator.
ANS: cout << setprecision( 3 ) << 1.92 << '\t' << 1.925 << '\t' << 1.9258;
t) Print integer 100 in octal, hexadecimal and decimal, using stream manipulators.
ANS: cout << oct << 100 << '\t' << hex << 100 << '\t' << dec << 100;
u) Print integer 100 in decimal, octal and hexadecimal, using a stream manipulator to
change the base.
ANS: cout << 100 << '\t' << setbase( 8 ) << 100 << '\t' << setbase( 16 ) << 100;
w) Read characters into character array line until the character 'z' is encountered, up to
a limit of 20 characters (including a terminating null character). Do not extract the delimiter character from the stream.
ANS: cin.get( line, 20, 'z' );
x) Use integer variables x and y to specify the field width and precision used to display the
double value 87.4573, and display the value.
15.4
Identify the error in each of the following statements and explain how to correct it.
a) cout << "Value of x <= y is: " << x <= y;
ANS: Error: The precedence of the << operator is higher than that of <=, which causes the
statement to be evaluated improperly and also causes a compiler error.
Correction: To correct the statement, place parentheses around the expression
x <= y. This problem will occur with any expression that uses operators of lower precedence than the << operator if the expression is not placed in parentheses.
b) The following statement should print the integer value of 'c'.
cout << 'c';
ANS: Error: In C++, characters are not treated as small integers, as they are in C.
Correction: To print the numerical value for a character in the computer's character
set, the character must be cast to an integer value, as in the following:
c)
ANS: Error: Quote characters cannot be printed in a string unless an escape sequence is
used.
Correction: Print the string in one of the following ways:
cout << '"' << "A string in quotes" << '"';
cout << "\"A string in quotes\"";
15.5
ANS: 12345
**123
b)
123
cout << setw( 10 ) << setfill( '$' ) << 10000;
ANS: $$$$$10000
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
ANS: 1024.988
d)
cout << showbase << oct << 99 << endl << hex << 99;
ANS: 0143
e)
0x63
cout << 100000 << endl << showpos << 100000;
ANS: 100000
f)
+100000
cout << setw( 10 ) << setprecision( 2 ) << scientific << 444.93738;
ANS:
4.45e+002
Exercises
15.6
e) Read characters into array charArray until the character 'p' is encountered, up to a limit of 10 characters (including the terminating null character). Extract the delimiter from
the input stream, and discard it.
<< setw( 9 )
g) Read a string of the form "characters" from the standard input. Store the string in
character array charArray. Eliminate the quotation marks from the input stream. Read
a maximum of 50 characters (including the terminating null character).
15.7 Write a program to test the inputting of integer values in decimal, octal and hexadecimal
formats. Output each integer read by the program in all three formats. Test the program with the
following input data: 10, 010, 0x10.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <string>
using std::string;
void show( const string message )
{
int integer; // holds values input by user
// prompt user to enter data in decimal format
cout << "\n" << message;
cin >> integer; // store data in integer
// display integer in decimal, octal and hexadecimal format
cout << showbase << "As a decimal number " << dec
<< integer << "\nAs an octal number " << oct << integer
<< "\nAs a hexadecimal number " << hex << integer << endl;
} // end function show
int main()
{
show( "Enter an integer: " );
cin >> oct;
show( "Enter an integer in ocal format: " );
cin >> hex;
show( "Enter an integer in hexadecimal format: " );
return 0;
} // end main
Enter an integer: 10
As a decimal number 10
As an octal number 012
As a hexadecimal number 0xa
Enter an integer in octal format: 010
As a decimal number 8
As an octal number 010
As a hexadecimal number 0x8
Enter an integer in hexadecimal format: 0x10
As a decimal number 16
As an octal number 020
As a hexadecimal number 0x10
15.8 Write a program that prints pointer values, using casts to all the integer data types. Which
ones print strange values? Which ones cause errors?
ANS:
1
2
3
4
5
6
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
<<
<<
<<
<<
<<
<<
<<
<<
<<
<<
*/
"Value of static_cast<char>(string) is
static_cast<char>( string ) << '\n'
"Value of static_cast<int>(string) is
static_cast<int>( string ) << '\n'
"Value of static_cast<long>(string) is
static_cast<long>( string ) << '\n'
"Value of static_cast<short>(string) is
static_cast<short>( string ) << '\n'
"Value of static_cast<unsigned>(string) is
static_cast<unsigned>( string )
: "
: "
: "
: "
: "
<< endl;
return 0;
} // end main
Value of string is
: test
Value of static_cast<void *>( string ) is
: 0046C080
15.9 Write a program to test the results of printing the integer value 12345 and the floating-point
value 1.2345 in various-sized fields. What happens when the values are printed in fields containing
fewer digits than the values?
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
15
16
17
18
19
20
21
22
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
printed
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
in
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
field
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
size 0 is
size 0 is
size 1 is
size 1 is
size 2 is
size 2 is
size 3 is
size 3 is
size 4 is
size 4 is
size 5 is
size 5 is
size 6 is
size 6 is
size 7 is
size 7 is
size 8 is
size 8 is
size 9 is
size 9 is
size 10 is
size 10 is
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
12345
1.2345
15.10 Write a program that prints the value 100.453627 rounded to the nearest digit, tenth, hundredth, thousandth and ten-thousandth.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10
18
19
20
21
22
Rounded
Rounded
Rounded
Rounded
Rounded
Rounded
to
to
to
to
to
to
0
1
2
3
4
5
digit(s)
digit(s)
digit(s)
digit(s)
digit(s)
digit(s)
is
is
is
is
is
is
100
100.5
100.45
100.454
100.4536
100.45363
15.11 Write a program that inputs a string from the keyboard and determines the length of the
string. Print the string in a length that is twice the field width.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
15.12 Write a program that converts integer Fahrenheit temperatures from 0 to
floating-point Celsius temperatures with 3 digits of precision. Use the formula
212
degrees to
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
...
Celsius
-17.778
-17.222
-16.667
-16.111
-15.556
+96.111
+96.667
+97.222
+97.778
+98.333
+98.889
+99.444
+100.000
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
11
12
15.13 In some programming languages, strings are entered surrounded by either single or double
quotation marks. Write a program that reads the three strings suzy, "suzy" and 'suzy'. Are the single and double quotes ignored or read as part of the string?
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
15.14 In Fig. 11.5, the stream extraction and stream insertion operators were overloaded for input
and output of objects of the PhoneNumber class. Rewrite the stream extraction operator to perform
the following error checking on input. The operator>> function will need to be reimplemented.
a) Input the entire phone number into an array. Test that the proper number of characters
has been entered. There should be a total of 14 characters read for a phone number of
the form (800) 555-1212. Use ios_base-member-function clear to set failbit for improper input.
b) The area code and exchange do not begin with 0 or 1. Test the first digit of the areacode and exchange portions of the phone number to be sure that neither begins with 0
or 1. Use ios_base-member-function clear to set failbit for improper input.
c) The middle digit of an area code used to be limited to 0 or 1 (although this has changed
recently). Test the middle digit for a value of 0 or 1. Use the ios_base-member-function
clear to set failbit for improper input. If none of the above operations results in failbit being set for improper input, copy the three parts of the telephone number into the
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
areaCode, exchange
13
and line members of the PhoneNumber object. In the main program, if failbit has been set on the input, have the program print an error message and
end, rather than print the phone number.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using std::istream;
using std::ostream;
class PhoneNumber
{
// overloaded input and output operators
friend ostream& operator<<( ostream&, const PhoneNumber& );
friend istream& operator>>( istream&, PhoneNumber& );
public:
PhoneNumber(); // default constructor
private:
char phone[ 15 ]; // holds phone number
char areaCode[ 4 ]; // holds area code
char exchange[ 4 ]; // holds exchange
char line[ 5 ]; // holds line
}; // end class PhoneNumber
#endif
#include <cstdlib>
using std::exit;
#include <cstring>
using std::strlen;
#include "PhoneNumber.h"
// PhoneNumber default constructor
PhoneNumber::PhoneNumber()
{
// set all char arrays to null character
phone[ 0 ] = '\0';
areaCode[ 0 ] = '\0';
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
exchange[ 0 ] = '\0';
line[ 0 ] = '\0';
} // end PhoneNumber constructor
// overloaded << operator
ostream &operator<<( ostream &output, const PhoneNumber &number )
{
// display PhoneNumber
output << "(" << number.areaCode << ") " << number.exchange
<< "-" << number.line << '\n';
return output; // return ostream reference
} // end overloaded << operator
// overloaded >> operator
istream &operator>>( istream &input, PhoneNumber &number )
{
// get phone number from input stream
input.getline( number.phone, 15 );
// validate length of PhoneNumber
if ( strlen( number.phone ) != 14 )
input.clear( ios::failbit );
// validate ( ) and if ( number.phone[ 0 ] != '(' || number.phone[ 4 ] != ')' ||
number.phone[ 9 ] != '-' )
input.clear( ios::failbit );
// validate first digit of area code and exchange
if ( number.phone[ 1 ] == '0' || number.phone[ 6 ] == '0' ||
number.phone[ 1 ] == '1' || number.phone[ 6 ] == '1')
input.clear( ios::failbit );
// validate middle digit of area code
if ( number.phone[ 2 ] != '0' && number.phone[ 2 ] != '1' )
input.clear( ios::failbit );
// if phone number is valid, set exchange and area code members
if ( !input.fail() )
{
int loop;
for ( loop = 0; loop <= 2; loop++ )
{
number.areaCode[ loop ] = number.phone[ loop + 1 ];
number.exchange[ loop ] = number.phone[ loop + 6 ];
} // end for
// place null-terminating character at end of area code and exchange
number.areaCode[ loop ] = number.exchange[ loop ] = '\0';
// set line class member
for ( loop = 0; loop <= 3; loop++ )
number.line[ loop ] = number.phone[ loop + 10 ];
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
77
78
79
80
81
82
83
84
85
86
87
88
89
90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
15
16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using std::ostream;
using std::istream;
class Point
{
// overloaded input and output operators
friend ostream &operator<<( ostream&, const Point& );
friend istream &operator>>( istream&, Point& );
private:
int xCoordinate; // x-coordinate of point pair
int yCoordinate; // y-coordiante of point pair
}; // end class Point
#endif
#include "Point.h"
// overloaded output (<<) operator
ostream& operator<<( ostream& out, const Point& p )
{
out << "(" << p.xCoordinate << ", " << p.yCoordinate << ")\n";
return out; // return ostream reference
} // end overloaded output (<<) operator
// overloaded input (>>) operator
istream& operator>>( istream& in, Point& p )
{
// validate first character entered and ignore if valid
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if ( in.peek() != '(' )
in.clear( ios::failbit ); // set failbit if invalid
else
{
in.ignore(); // skip (
in >> p.xCoordinate; // next character is x-coordinate
// validate third character and skip if valid
if ( in.peek() != ',' )
in.clear( ios::failbit ); // set failbit if invalid
else
{
in.ignore(); // skip ,
// validate fourth character and skip if valid
if ( in.peek() != ' ' )
in.clear( ios::failbit ); // set failbit if invalid
else
{
in.ignore(); // skip space
in >> p.yCoordinate; // next character is y-coordinate
// validate last character and skip if valid
if ( in.peek() != ')' )
in.clear( ios::failbit ); // set failbit if invalid
else
in.ignore(); // skip )
} // end else
} // end else
} // end else
return in; // return istream reference
} // end overloaded input (>>) operator
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
17
18
20
21
22
23
24
else
cout << "\nInvalid data\n"; // tell user invalid data was entered
return 0;
} // end main
c) The values can be negative or positive, and it is possible that one of the two values is not
provided. If a value is not provided, the appropriate data member should be set to 0.
The stream-insertion operator should not be able to display the point if an input error
occurred. For negative imaginary values, a minus sign should be printed rather than a
plus sign.
d) Write a main function that tests input and output of user-defined class Complex, using
the overloaded stream extraction and stream insertion operators.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
19
20
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
21
22
23
24
21
15.17 Write a program that uses a for statement to print a table of ASCII values for the characters
in the ASCII character set from 33 to 126. The program should print the decimal value, octal value,
hexadecimal value and character value for each character. Use the stream manipulators dec, oct and
hex to print the integer values.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
22
Decimal
33
34
35
36
37
38
39
40
...
118
119
120
121
122
123
124
125
126
Octal
041
042
043
044
045
046
047
050
Hexadecimal
0x21
0x22
0x23
0x24
0x25
0x26
0x27
0x28
Character
!
"
#
$
%
&
'
(
0166
0167
0170
0171
0172
0173
0174
0175
0176
0x76
0x77
0x78
0x79
0x7a
0x7b
0x7c
0x7d
0x7e
v
w
x
y
z
{
|
}
~
15.18 Write a program to show that the getline and three-argument get istream member functions both end the input string with a string-terminating null character. Also, show that get leaves
the delimiter character on the input stream, whereas getline extracts the delimiter character and
discards it. What happens to the unread characters in the stream?
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
28
29
30
cout << "The next character in the input is: " << c << '\n';
return 0;
} // end main
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
23