CS 173 Lab 5: Output Formatting and File I/O
Objective:
In class we discussed using ifstream and ofstream for file
input/output. We have also seen if statements and boolean expressions.
For this lab you will practice writing C++ programs that incorporate
these techniques, and also begin writing robust programs --- programs
that can detect and react to problems when they occur.
Additional info: You can use an ifstream or ofstream object
as a boolean expression. When you do, it evaluates to true
if all previous operations using the object were successful, otherwise
it evaluates to false. You can also call the function exit(1)
to immediately terminate the execution of your program. This is extremely
useful. Observe the following code:
string ifName = "data.in";
int i;
// Open the input file
inFile.open(ifName.c_str());
// If the file did not open successfully, we want to display
// a useful message for the user and quit the program.
if (!inFile)
{
cout << "ERROR: Unable to open " << ifName << endl;
cout << "Exiting program." << endl;
exit(1);
}
inFile >> i;
if (!inFile)
{
cout << "ERROR: Unable to read an integer from " << ifName << endl;
cout << "Exiting program." << endl;
exit(1);
}
From this point on, you should use this kind of "if" statement to
ensure that your files successfully opened, and that each read of
data was successful. If not, then print a helpful error message and
terminate your program.
Lab Tasks
This week you will write a C++ program called stocktrack_fileio.cpp.
This program is exactly like last week's
(
http://webpages.ursinus.edu/rliston/cs173/lab4.html), except input and
output will be to/from files (no prompts are necessary) and your programs
must be robust. The program will read a series of 10 closing bell values
of a particular stock from a file named "stock.in".
The program will then print to the a file called "stock.out" a series of
lines exactly like last week's program.
Make sure you define the three integer constants that indicate the
field widths. These must be based on the length of the string for the
column heading using the .length() function. Use those field widths as
arguments to each setw().
Finally, this week I would like to see the checklists that you are
maintaining of the things *you* need to watch out for in your coding.
Check through this list before compiling and add to it as you discover
errors.
Notes:
-
As always, this lab is due by 9am Friday.
-
Remember to put the comments you need at the top of your source file.
-
Format your code for readability. (See the Coding Standard.)
-
Use meaningful names for your identifiers.
-
Comment each item that is declared.
-
Email your program and checklist as attachments to
rliston at ursinus dot edu.
Use a subject line of: "CS 173 Lab 5".
Richard Liston