Handout - Using files
// program converts yards to feet and inches
// input and output using files
// Problem 3 (part 1), page 95
#include <fstream> // provides ifstream, ofstream
#include <iostream> // provides cout
#include <iomanip> // provides setw
#include <cstdlib> // provides exit()
using namespace std;
int main()
{
// declare file variables
ifstream infile;
ofstream outfile;
// associate file variables with specific files
infile.open("yards.in");
outfile.open("length.out");
// make sure that both files exist
if (!infile){
cout << "Unable to open input file" << endl;
exit(0);
}
if (!outfile){
cout << "Unable to open output file" << endl;
exit (0);
}
// write headings to output file
outfile << "YARDS FEET INCHES" << endl;
outfile << "---------------------" << endl;
int yards, feet, inches;
// read in the next value for yard, if there is one
while (infile >> yards){
// convert to feet and inches
feet = yards * 3;
inches = yards * 36;
// write results to the output file
outfile << setw(5) << yards << setw(7) << feet << setw(9) << inches << endl;
}
// close the files
infile.close();
outfile.close();
return 0;
}