You are on page 1of 23

15

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

All the news thats t to


print.
Adolph S. Ochs

Remove not the landmark


on the boundary of the elds.
Amenehope

OBJECTIVES
In this chapter you will learn:

To use C++ object-oriented stream input/output.

To format input and output.

The stream-I/O class hierarchy.

To use stream manipulators.

To control justication and padding.

To determine the success or failure of input/output


operations.
To tie output streams to input streams.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 15 Stream Input/Output

Self-Review Exercises
15.1

Answer each of the following:


a) Input/output in C++ occurs as
of bytes.
ANS: streams.
b) The stream manipulators that format justification are
.
ANS: left, right and internal.

can be used to set and reset format state.

c) Member function

ANS: flags.

d) Most C++ programs that do I/O should include the


tains the declarations required for all stream-I/O operations.

header file that con-

ANS: <iostream>.

e) When using parameterized manipulators, the header file

ANS: <iomanip>.

f) Header file
cessing.

and

must be included.

contains the declarations required for user-controlled file pro-

ANS: <fstream>.

g) The ostream member function

ANS: write.

is used to perform unformatted output.

h) Input operations are supported by class


ANS: istream.

i) Outputs to the standard error stream are directed to either the


stream object.
ANS: cerr or clog.

j) Output operations are supported by class


ANS: ostream.

k) The symbol for the stream insertion operator is

ANS: <<.

or the

.
.

l) The four objects that correspond to the standard devices on the system include
,
,
and
.
ANS: cin, cout, cerr and clog.

m) The symbol for the stream extraction operator is


ANS: >>.

n) The stream manipulators


,
and
specify that integers should be displayed in octal, hexadecimal and decimal formats, respectively.
ANS: oct, hex and dec.

o) When used, the


with a plus sign.

stream manipulator causes positive numbers to display

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

Chapter 15 Stream Input/Output


For each of the following, write a single statement that performs the indicated task.
a) Output the string "Enter your name: ".
ANS: cout << "Enter your name: ";

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;

c) Output the address of the variable myString of type char *.


ANS: cout << static_cast< void * >( myString );

d) Use a stream manipulator to ensure floating-point values print in scientific notation.


ANS: cout << scientific;

e) Output the address in variable integerPtr of type int *.


ANS: cout << integerPtr;

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;

g) Output the value pointed to by floatPtr of type float *.


ANS: cout << *floatPtr;

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( '*' );

i) Output the characters

'O'

and 'K' in one statement with ostream function put.

ANS: cout.put( 'O' ).put( 'K' );

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

and a floating-point value into float

ANS: cin >> months >> percentageRate;

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;

v) Print 1234 right justified in a 10-digit field.


ANS: cout << setw( 10 ) << 1234;

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.

ANS: cout << setw( x ) << setprecision( y ) << 87.4573;

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)

cout << static_cast< int >( 'c' );


cout << ""A string in quotes"";

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

For each of the following, show the output.


a) cout << "12345" << endl;
cout.width( 5 );
cout.fill( '*' );
cout << 123 << endl << 123;

ANS: 12345
**123

b)

123
cout << setw( 10 ) << setfill( '$' ) << 10000;

ANS: $$$$$10000

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 15 Stream Input/Output


c)

cout << setw( 8 ) << setprecision( 3 ) << 1024.987654;

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

Write a statement for each of the following:


a) Print integer 40000 left justified in a 15-digit field.
ANS: cout << left << setw( 15 ) << 40000 << '\n';

b) Read a string into character array variable state.


ANS: cin >> state;

c) Print 200 with and without a sign.


ANS: cout << showpos << 200 << setw( 4 )

<< '\n' << noshowpos << 200 << '\n';

d) Print the decimal value 100 in hexadecimal form preceded by 0x.


ANS: cout << showbase << hex << 100 << '\n';

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.

ANS: cin.getline( charArray, 10, 'p' );

f) Print 1.234 in a 9-digit field with preceding zeros.

ANS: cout << fixed << showpoint

<< setw( 9 )

<< setfill( '0' ) << internal << 1.234 << '\n';

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

// Exercise 15.7 Solution: Ex15_07.cpp


#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::ios;
#include <iomanip>
using std::dec;
using std::hex;
using std::oct;
using std::showbase;

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

// Exercise 15.8 Solution: Ex15_08.cpp


#include <iostream>
using std::cout;
using std::endl;
int main()

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

Chapter 15 Stream Input/Output

// string to cast into integer formats


char *string = "test";
// display data stored in string and
// address of string using static_cast
cout << "Value of string is
: " << string << '\n'
<< "Value of static_cast<void *>( string ) is
: "
<< static_cast<void *>( string ) << '\n'
// The following generate errors.
// reinterpret_cast will allow this type of casting.
// See Ch. 24 for a discussion of reinterpret_cast.

/*

<<
<<
<<
<<
<<
<<
<<
<<
<<
<<

*/

"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

// Exercise 15.9 Solution: Ex15_09.cpp


#include <iostream>
using std::cout;
#include <iomanip>
using std::setw;
int main()
{
// values used for testing output in various field lengths
int x = 12345;
double y = 1.2345;
// display values in fields the size of loop counter

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
15
16
17
18
19
20
21
22

for ( int loop = 0; loop <= 10; loop++ )


cout << x << " printed in a field of size " << setw( 2 )
<< loop << " is " << setw( loop ) << x << '\n' << y
<< " printed in a field of size " << setw( 2 )
<< loop << " is " << setw( loop ) << y << '\n';
return 0;
} // end main

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

// Exercise 15.10 Solution: Ex15_10.cpp


#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setprecision;
using std::fixed;
int main()
{
double x = 100.453627; // value to test precision outputs
cout << fixed; // display output using fixed-point notation
// display output using loop counter as precision
for ( int loop = 0; loop <= 5; loop++ )

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10
18
19
20
21
22

Chapter 15 Stream Input/Output

cout << setprecision( loop ) << "Rounded to " << loop


<< " digit(s) is " << x << endl;
return 0;
} // end main

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

// Exercise 15.11 Solution: Ex15_11.cpp


#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
#include <string>
using std::string;
int main()
{
string input; // string to hold input string
int stringLength; // variable used to hold length of string
// ask user for string and store in character array
cout << "Enter a string: ";
cin >> input;
stringLength = input.length(); // get length of string
// display length of string
cout << "the length of the string is " << stringLength << endl;
// print string using twice the length as field with
cout << setw( 2 * stringLength ) << input << endl;
return 0;
} // end main

Enter a string: castle


the length of the string is 6
castle

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

celsius = 5.0 / 9.0 * ( fahrenheit - 32 );

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

...

// Exercise 15.12 Solution: Ex15_12.cpp


#include <iostream>
using std::cout;
#include <iomanip>
using std::fixed;
using std::noshowpos;
using std::setprecision;
using std::setw;
using std::showpoint;
using std::showpos;
int main()
{
double celsius; // holds Celsius temperature
// create column headings with fields of length 20
cout << setw( 20 ) << "Fahrenheit " << setw( 20 ) << "Celsius\n"
<< fixed << showpoint;
// convert Fahrenheit to Celsius and display temperatures
// showing the sign for Celsius temperatures
for ( int fahrenheit = 0; fahrenheit <= 212; fahrenheit++ )
{
celsius = 5.0 / 9.0 * ( fahrenheit - 32 );
cout << setw( 15 ) << noshowpos << fahrenheit << setw( 23 )
<< setprecision( 3 ) << showpos << celsius << '\n';
} // end for
return 0;
} // end main
Fahrenheit
0
1
2
3
4
205
206
207
208
209
210
211
212

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

Chapter 15 Stream Input/Output

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

// Exercise 15.13 Solution: Ex15_13.cpp


#include <iostream>
using std::cin;
using std::cout;
#include <string>
using std::string;
int main()
{
string input; // string to hold input string
// ask user to enter three strings and then
// store and display the strings
for ( int k = 0; k < 3; k++ )
{
cout << "Enter a string: ";
cin >> input;
cout << "String is " << input << '\n';
} // end for
return 0;
} // end main

Enter a string: suzy


String is suzy
Enter a string: 'suzy'
String is 'suzy'
Enter a string: "suzy"
String is "suzy"

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

// Exercise 15.14 Solution: PhoneNumber.h


#ifndef PHONENUMBER_H
#define PHONENUMBER_H

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

// Exercise 15.14 Solution: PhoneNumber.cpp


// Member function definition of class PhoneNumber
#include <iostream>
using std::cerr;
using std::ios;
using std::istream;
using std::ostream;

#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

Chapter 15 Stream Input/Output

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

// place null-terminating character at end of line array


number.line[ loop ] = '\0';
} // end if
// if phone number is invalid, tell user and terminate application
else
{
cerr << "Invalid phone number entered.\n";
exit( 1 );
} // end else
return input; // return istream reference
} // end overloaded >> operator

// Exercise 15.14 Solution: Ex15_14.cpp


// PhoneNumber test program
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include "PhoneNumber.h"
int main()
{
PhoneNumber telephone; // create PhoneNumber object
// ask user to enter valid telephone number and store it
cout << "Enter a phone number in the form (123) 456-7890:\n";
cin >> telephone;
// display phone number entered by user
cout << "The phone number entered was: " << telephone << endl;
// ask user for invalid phone number and store it
cout << "Now enter an invalid phone number:\n";
cin >> telephone;
return 0;
} // end main

Enter a phone number in the form (123) 456-7890:


(800) 987-4567
The phone number entered was: (800) 987-4567
Now enter an invalid phone number:
(000) 000-0000
Invalid phone number entered.

15.15 Write a program that accomplishes each of the following:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

15

16

Chapter 15 Stream Input/Output


a) Create a user-defined class Point that contains the private integer data members xCoordinate and yCoordinate and declares stream insertion and stream extraction overloaded
operator functions as friends of the class.
b) Define the stream insertion and stream extraction operator functions. The stream extraction operator function should determine whether the data entered is valid, and, if
not, it should set the failbit to indicate improper input. The stream insertion operator
should not be able to display the point after an input error occurred.
c) Write a main function that tests input and output of user-defined class Point, 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

// Exercise 15.15 Solution: Point.h


#ifndef POINT_H
#define POINT_H

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

// Exercise 15.15 Solution: Point.cpp


// Member function definition of class Point.
#include <iostream>
using std::ios;
using std::istream;
using std::ostream;

#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

// Exercise 15.15 Solution: Ex15_15.cpp


// Point test program.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include "Point.h"
int main()
{
Point pt; // create point object
// ask user to enter point
cout << "Enter a point in the form (x, y):\n";
cin >> pt; // store user entered point
if ( !cin.fail() ) // validate input
cout << "Point entered was: " << pt << endl; // display point

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

17

18
20
21
22
23
24

Chapter 15 Stream Input/Output

else
cout << "\nInvalid data\n"; // tell user invalid data was entered
return 0;
} // end main

Enter a point in the form (x, y):


(7, 8)
Point entered was: (7, 8)

15.16 Write a program that accomplishes each of the following:


a) Create a user-defined class Complex that contains the private integer data members real
and imaginary and declares stream insertion and stream extraction overloaded operator
functions as friends of the class.
b) Define the stream insertion and stream extraction operator functions. The stream extraction operator function should determine whether the data entered is valid, and, if
not, it should set failbit to indicate improper input. The input should be of the form
3 + 8i

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

// Exercise 15.16 Solution: Complex.h


#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
using std::ostream;
using std::istream;
class Complex
{
// overloaded input and output operators
friend ostream &operator<<( ostream&, const Complex& );
friend istream &operator>>( istream&, Complex& );
public:
Complex( void ); // constructor
private:
int real; // hold real part of complex number
int imaginary; // hold imaginary part of complex number
}; // end class Complex
#endif

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

// Exercise 15.16 Solution: Complex.cpp


// Member-function definition of class Complex.
#include <iostream>
using std::ios;
using std::istream;
using std::ostream;
#include <iomanip>
using std::showpos;
#include "Complex.h"
// default constructor
Complex::Complex( void ):
real( 0 ),
imaginary( 0 )
{
// empty body
} // end Complex constructor
// overloaded output (<<) operator
ostream &operator<<( ostream &output, const Complex &c )
{
output << c.real << showpos << c.imaginary << "i\n" << showpos;
return output; // return ostream reference
} // end overloaded output (<<) operator
// overloaded input (>>) operator
istream &operator>>( istream &input, Complex &c )
{
int number;
int multiplier;
char temp; // temporary variable used to store input
input >> number; // get input
// test if character is a space
if ( input.peek() == ' ' ) // case a + bi
{
c.real = number;
input >> temp;
multiplier = ( temp == '+' ) ? 1 : -1;
// set failbit if character not a space
if ( input.peek() != ' ' )
input.clear( ios::failbit ); // set bad bit
else
{
// set imaginary part if data is valid
if ( input.peek() == ' ' )
{
input >> c.imaginary;
c.imaginary *= multiplier;

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

Chapter 15 Stream Input/Output

input >> temp;


if ( input.peek() != '\n' ) // character not a newline
input.clear( ios::failbit ); // set bad bit
} // end if
else
input.clear( ios::failbit ); // set bad bit
} // end else
} // end if
else if ( input.peek() == 'i' ) // test for i of imaginary number
{
input >> temp;
// test for newline character entered
if ( input.peek() == '\n' )
{
c.real = 0;
c.imaginary = number;
} // end if
else
input.clear( ios::failbit ); // set bad bit
} // end else if
else if ( input.peek() == '\n' ) // set real number if it is valid
{
c.real = number;
c.imaginary = 0;
} // end else if
else
input.clear( ios::failbit ); // set bad bit
return input;
} // end overloaded input (>>) operator

// Exercise 15.16 Solution: Ex15_16.cpp


// Complex test program.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include "Complex.h"
int main()
{
Complex complex; // create Complex object
// ask user to enter complex number
cout << "Input a complex number in the form A + Bi:\n";
cin >> complex; // store complex number
if ( !cin.fail() ) // display complex number entered by user if valid
cout << "Complex number entered was:\n" << complex << endl;
else

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
21
22
23
24

21

cout << "Invalid Data Entered\n";


return 0;
} // end main

Input a complex number in the form A + Bi:


7 - 777i
Complex number entered was:
7-777i

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

// Exercise 15.17 Solution: Ex15_17.cpp


#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::dec;
using std::hex;
using std::oct;
using std::setw;
using std::showbase;
int main()
{
// display column headings and set field lengths
cout << setw( 7 ) << "Decimal" << setw( 9 ) << "Octal " << setw( 15 )
<< "Hexadecimal " << setw( 13 ) << "Character" << showbase << '\n';
// loop through ASCII values 33-126 and display corresponding
// integer, octal and hexadecimal values
for ( int loop = 33; loop <= 126; loop++ )
cout << setw( 7 ) << dec << loop << setw( 9 ) << oct << loop
<< setw( 15 ) << hex << loop << setw(13)
<< static_cast< char >( loop ) << endl;
return 0;
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

22

Chapter 15 Stream Input/Output

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

// Exercise 15.18 Solution: Ex15_18.cpp


#include <iostream>
using std::cin;
using std::cout;
using std::endl;
const int SIZE = 80;
int main()
{
char array[ SIZE ]; // array to hold getline() input
char array2[ SIZE ]; // array to hold get() input
char c;// holds next input value
// prompt user to enter string and use getline() to store it
cout << "Enter a sentence to test getline() and get():\n";
cin.getline( array, SIZE, '*' );
cout << array << '\n';
cin >> c; // read next character in input
cout << "The next character in the input is: " << c << '\n';
// use get() to obtain next value held in array
cin.get( array2, SIZE, '*' );
cout << array2 << '\n';
cin >> c; // read next character in input

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

Enter a sentence to test getline() and get():


wishing*on*a*star
wishing
The next character in the input is: o
n
The next character in the input is: *

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

23

You might also like