Chapter 3 Exercise

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Exercises | 171

16. The manipulator setprecision formats the output of floating-point


numbers to a specified number of decimal places.
17. The manipulator fixed outputs floating-point numbers in the fixed
decimal format.
18. The manipulator showpoint outputs floating-point numbers with a
decimal point and trailing zeros.
19. The manipulator setw formats the output of an expression in a specific 3
number of columns; the default output is right-justified.
20. If the number of columns specified in the argument of setw is less than the
number of columns needed to print the value of the expression, the output
is not truncated and the output of the expression expands to the required
number of columns.
21. The manipulator setfill is used to fill the unused columns on an output
device with a character other than a space.
22. If the number of columns specified in the setw manipulator exceeds the
number of columns required by the next expression, the output is right-
justified. To left-justify the output, you use the manipulator left.
23. To use the stream functions get, ignore, putback, peek, clear, and unsetf
for standard I/O, the program must include the header file iostream.
24. To use the manipulators setprecision, setw, and setfill, the program
must include the header file iomanip.
25. The header file fstream contains the definitions of ifstream and ofstream.
26. For file I/O, you must use the statement #include <fstream> to include the
header file fstream in the program. You must also do the following: declare
variables of type ifstream for file input and of type ofstream for file output
and use open statements to open input and output files. You can use <<, >>,
get, ignore, peek, putback, or clear with file stream variables.
27. To close a file as indicated by the ifstream variable inFile, you use the
statement inFile.close();. To close a file as indicated by the ofstream
variable outFile, you use the statement outFile.close();.

EXERCISES
1. Mark the following statements as true or false.
a. The extraction operator >> skips all leading whitespace characters when
searching for the next data in the input stream.
b. In the statement cin >> x;, x must be a variable.
c. The statement cin >> x >> y; requires the input values for x and y to
appear on the same line.
172 | Chapter 3: Input/Output

d. The statement cin >> num; is equivalent to the statement num >> cin;.
e. You generate the newline character by pressing the Enter (return) key
on the keyboard.
f. The function ignore is used to skip certain input in a line.
2. Suppose num1 and num2 are int variables and symbol is a char variable.
Consider the following input:
47 18 * 28 $
What value (if any) is assigned to num1, num2, and symbol after each of the
following statements executes? (Use the same input for each statement.)
a. cin >> num1 >> symbol >> num2;
b. cin >> symbol >> num1 >> num2;
c. cin >> num1;
cin.get (symbol);
cin >> num2;
d. cin >> num1 >> num2;
cin.get (symbol);
e. cin.get (symbol);
cin >> num1 >> num2;
3. Suppose x and y are int variables and z is a double variable. Assume the
following input data:
37 86.56 32
What value (if any) is assigned to x, y, and z after each of the following
statements executes? (Use the same input for each statement.)
a. cin >> x >> y >> z;
b. cin >> x >> z >> y;
c. cin >> z >> x >> y;

4. Suppose x and y are int variables and symbol is a char variable. Assume
the following input data:
38 26 * 67 33
24 $ 55 # 34
# & 63 85

What value (if any) is assigned to x, y, and symbol after each of the
following statements executes? (Use the same input for each statement.)
a. cin >> x >> y;
cin.ignore(100, '\n');
cin >> symbol;
b. cin >> x;
cin.ignore(100, '*');
cin >> y;
cin.get(symbol);
Exercises | 173

c. cin >> y;
cin.ignore(100, '\n');
cin >> x >> symbol;
d. cin.get(symbol);
cin.ignore(100, '*');
cin >> x;
cin.ignore(100, '\n');
cin >> y;
3
e. cin.ignore(100, '\n');
cin >> x >> symbol;
cin.ignore(100, '\n');
cin.ignore(100, '&');
cin >> y;

5. Given the input:


46 A 49

and the C++ code:


int x = 10, y = 18;
char z = '*';
cin >> x >> y >> z;
cout << x << " " << y << " " << z << endl;

What is the output?


6. Suppose that x and y are int variables, z is a double variable, and ch is a
char variable. Suppose the input statement is:
cin >> x >> y >> ch >> z;

What values, if any, are stored in x, y, z, and ch if the input is:


a. 35 62.78
b. 86 32A 92.6
c. 12 .45A 32

7. Which header file must be included to use the function steprecision?


8. Which header file must be included to use the function pow?
9. Which header file must be included to use the function sqrt?
10. What is the output of the following program?
#include <iostream>
#include <cmath>
#include <string>

using namespace std;


174 | Chapter 3: Input/Output

int main()
{
int x, y;
string message;
double z;

x = 4;
y = 3;
z = 2.5;

cout << static_cast<int>(pow(x, 2.0)) << endl;


cout << static_cast<int>(pow(z, y)) << endl;

cout << pow(x, z) << endl;

cout << sqrt(36.0) << endl;

z = pow(9.0, 2.5);
cout << z << endl;

message = "Using C++ predefined function";

cout << "Length of message = "


<< message.length() << endl;

return 0;
}
11. To use the functions peek and putback in a program, which header file(s)
must be included in the program?
12. Suppose that num is an int variable and discard is a char variable.
Assume the following input data:
#34
What value (if any) is assigned to num and discard after each of the
following statements executes? (Use the same input for each statement.)
a. cin.get (discard);
cin >> num;
b. discard = cin.peek();
cin >> num;
c. cin.get (discard);
cin.putback (discard);
cin >> discard;
cin >> num;
13. Suppose that name is a variable of type string. Write the input statement
to read and store the input Brenda Clinton in name. (Assume that the
input is from the standard input device.)
Exercises | 175

14. Write a C++ statement that uses the manipulator setfill to output a line
containing 35 stars, as in the following line:
***********************************
15. Suppose that age is an int variable and name is a string variable. What are
the values of age and name after the following input statements execute:
cin >> age;
getline(cin, name); 3
if the input is:
a. 23 Lance Grant
b. 23
Lance Grant

16. Suppose that age is an int variable, ch is a char variable, and name is a
string variable. What are the values of age and name after the following
input statements execute:
cin >> age;
cin.get(ch);
getline(cin, name);

if the input is:


a. 23 Lance Grant
b. 23
Lance Grant
17. The following program is supposed to read two numbers from a file named
input.dat and write the sum of the numbers to a file named output.dat.
However, it fails to do so. Rewrite the program so that it accomplishes what
it is intended to do. (Also, include statements to close the files.)
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
int num1, num2;
ifstream infile;

outfile.open("output.dat");
infile >> num1 >> num2;
outfile << "Sum = " << num1 + num2 << endl;
return 0;
}
176 | Chapter 3: Input/Output

18. What may cause an input stream to enter the fail state? What happens when
an input stream enters the fail state?
19. Which header file needs to be included in a program that uses the data types
ifstream and ofstream?
20. Suppose that infile is an ifstream variable and employee.dat is a file
that contains employees’ information. Write the C++ statement that opens
this file using the variable infile.
21. A program reads data from a file called inputFile.dat and, after doing
some calculations, writes the results to a file called outFile.dat. Answer
the following questions:
a. After the program executes, what are the contents of the file
inputFile.dat?
b. After the program executes, what are the contents of the file outFile.dat if
this file was empty before the program executed?
c. After the program executes, what are the contents of the file outFile.dat if
this file contained 100 numbers before the program executed?
d. What would happen if the file outFile.dat did not exist before the
program executed?
22. Suppose that infile is an ifstream variable and it is associated with the
file that contains the following data: 27306 savings 7503.35. Write the
C++ statement(s) that reads and stores the first input in the int variable
acctNumber, the second input in the string variable accountType, and
the third input in the double variable balance.
23. Suppose that you have the following statements:
ofstream outfile;
double distance = 375;
double speed = 58;
double travelTime;

Write C++ statements to do the following:


a. Open the file travel.dat using the variable outfile.
b. Write the statement to format your output to two decimal places in
fixed form.
c. Write the values of the variables day, distance, and speed in the file
travel.dat.
d. Calculate and write the travelTime in the file travel.dat.
e. Which header files are needed to process the information in (a) to (d)?
Programming Exercises | 177

PROGRAMMING EXERCISES
1. Consider the following incomplete C++ program:
#include <iostream>

int main()
{
... 3
}

a. Write a statement that includes the header files fstream, string, and
iomanip in this program.
b. Write statements that declare inFile to be an ifstream variable and
outFile to be an ofstream variable.
c. The program will read data from the file inData.txt and write output to
the file outData.txt. Write statements to open both of these files, associate
inFile with inData.txt, and associate outFile with outData.txt.
d. Suppose that the file inData.txt contains the following data:
10.20 5.35
15.6
Randy Gill 31
18500 3.5
A

The numbers in the first line represent the length and width, respectively, of
a rectangle. The number in the second line represents the radius of a circle.
The third line contains the first name, last name, and the age of a person. The
first number in the fourth line is the savings account balance at the beginning
of the month, and the second number is the interest rate per year. (Assume
that p ¼ 3.1416.) The fifth line contains an uppercase letter between A and
Y (inclusive). Write statements so that after the program executes, the con-
tents of the file outData.txt are as shown below. If necessary, declare
additional variables. Your statements should be general enough so that if the
content of the input file changes and the program is run again (without
editing and recompiling), it outputs the appropriate results.
Rectangle:
Length = 10.20, width = 5.35, area = 54.57, parameter = 31.10

Circle:
Radius = 15.60, area = 764.54, circumference = 98.02

Name: Randy Gill, age: 31


Beginning balance = $18500.00, interest rate = 3.50
Balance at the end of the month = $18553.96

The character that comes after A in the ASCII set is B


178 | Chapter 3: Input/Output

e. Write statements that close the input and output files.


f. Write a C++ program that tests the statements in parts a through e.
2. Consider the following program in which the statements are in the incorrect
order. Rearrange the statements so that the program prompts the user to input
the height and the radius of the base of a cylinder and outputs the volume and
surface area of the cylinder. Format the output to two decimal places.
#include <iomanip>
#include <cmath>

int main()
{}

double height;

cout << "Volume of the cylinder = "


<< PI * pow(radius, 2.0)* height << endl;

cout << "Enter the height of the cylinder: ";


cin >> radius;
cout << endl;

return 0;

double radius;

cout << "Surface area: "


<< 2 * PI * radius * height + 2 * PI * pow(radius, 2.0)
<< endl;
cout << fixed << showpoint << setprecision(2);

cout << "Enter the radius of the base of the cylinder: ";
cin >> height;
cout << endl;

#include <iostream>
const double PI = 3.14159;

using namespace std;


3. Write a program that prompts the user to enter the weight of a person in
kilograms and outputs the equivalent weight in pounds. Output both the
weights rounded to two decimal places. (Note that 1 kilogram ¼ 2.2
pounds.) Format your output with two decimal places.
4. During each summer, John and Jessica grow vegetables in their backyard
and buy seeds and fertilizer from a local nursery. The nursery carries
different types of vegetable fertilizers in various bag sizes. When buying a
particular fertilizer, they want to know the price of the fertilizer per pound
and the cost of fertilizing per square foot. The following program prompts
Programming Exercises | 179

the user to enter the size of the fertilizer bag, in pounds, the cost of the bag,
and the area, in square feet, that can be covered by the bag. The program
should output the desired result. However, the program contains logic
errors. Find and correct the logic errors so that the program works properly.
//Logic errors.

#include <iostream>
#include <iomanip>
3
using namespace std;

int main()
{
double cost;
double area;

double bagSize;

cout << fixed << showpoint << setprecision(2);

cout << "Enter the amount of fertilizer, in pounds, "


<< "in one bag: ";
cin >> bagSize;
cout << endl;

cout << "Enter the cost of the " << bagSize


<< " pound fertilizer bag: ";
cin >> cost;
cout << endl;

cout << "Enter the area, in square feet, that can be "
<< "fertilized by one bag: ";
cin >> area;
cout << endl;

cout << "The cost of the fertilizer per pound is: $"
<< bagSize / cost << endl;
cout << "The cost of fertilizing per square foot is: $"
<< area / cost << endl;

return 0;
}

5. The manager of a football stadium wants you to write a program that


calculates the total ticket sales after each game. There are four types of
tickets—box, sideline, premium, and general admission. After each game,
data is stored in a file in the following form:
ticketPrice numberOfTicketsSold
...
180 | Chapter 3: Input/Output

Sample data are shown below:

250 5750
100 28000
50 35750
25 18750

The first line indicates that the ticket price is $250 and that 5750 tickets were
sold at that price. Output the number of tickets sold and the total sale
amount. Format your output with two decimal places.
6. Redo Programming Exercise 21, in Chapter 2, so that each string can store
a line of text.
7. Three employees in a company are up for a special pay increase. You are
given a file, say Ch3_Ex7Data.txt, with the following data:

Miller Andrew 65789.87 5


Green Sheila 75892.56 6
Sethi Amit 74900.50 6.1

Each input line consists of an employee’s last name, first name, current salary,
and percent pay increase. For example, in the first input line, the last name of
the employee is Miller, the first name is Andrew, the current salary is
65789.87, and the pay increase is 5%. Write a program that reads data from
the specified file and stores the output in the file Ch3_Ex7Output.dat.
For each employee, the data must be output in the following form:
firstName lastName updatedSalary. Format the output of decimal
numbers to two decimal places.
8. Write a program that accepts as input the mass, in grams, and density, in
grams per cubic centimeters, and outputs the volume of the object using the
formula: volume ¼ mass / density. Format your output to two decimal places.
9. Interest on a credit card’s unpaid balance is calculated using the average daily
balance. Suppose that netBalance is the balance shown in the bill, payment is
the payment made, d1 is the number of days in the billing cycle, and d2
is the number of days payment is made before billing cycle. Then, the
average daily balance is:

averageDailyBalance ¼ ðnetBalance  d1  payment  d2Þ=d1

If the interest rate per month is, say, 0.0152, then the interest on the
unpaid balance is:

interest ¼ averageDailyBalance  0:0152


Programming Exercises | 181

Write a program that accepts as input netBalance, payment, d1, d2, and interest
rate per month. The program outputs the interest. Format your output to two
decimal places.
10. Linda is starting a new cosmetic and clothing business and would like to
make a net profit of approximately 10% after paying all the expenses, which
include merchandise cost, store rent, employees’ salary, and electricity cost
for the store. She would like to know how much the merchandise should 3
be marked up so that after paying all the expenses at the end of the year she
gets approximately 10% net profit on the merchandise cost. Note that after
marking up the price of an item she would like to put the item on 15% sale.
Write a program that prompts Linda to enter the total cost of the merchan-
dise, the salary of the employees (including her own salary), the yearly rent,
and the estimated electricity cost. The program then outputs how much the
merchandise should be marked up so that Linda gets the desired profit.

You might also like