Lab 5 Objectives: Reading from and Writing to files Create a data file of the fo
ID: 3543124 • Letter: L
Question
Lab 5
Objectives: Reading from and Writing to files
Create a data file of the following integers:
10 20 30
17 21 18
30 20 49
40 25 35
55 45 35
25 55 5
-1 -1 -1
Create an input file and an output file. Read the data, 3 values at a time, from the input file until you read the sentinel data line. Arrange the three values that have been read in order from lowest to highest, and then write the set of three numbers to the output file. Use a series of if statements to find the smallest, the middle value, and the largest. When all lines of data have been processed, close both files. Then reopen the output file as input
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile("input.txt");
ofstream outfile("output.txt");
int value1,value2,value3;
if(!infile)
{
cout <<"Unable to open file. so Exiting from program " << endl;
return 0;
}
while(!infile.eof())
{
infile >> value1 >> value2 >> value3;
if(value1==-1) break;
int max= value1;
if(value2>max) max = value2;
if(value3>max) max = value3;
int min= value1;
if(value2<min) min = value2;
if(value3<min) min = value3;
outfile << min << " " << (value1+value2+value3-max-min) << " " << max << endl;
}
infile.close();
outfile.close();
ifstream file2("output.txt");
if(!file2)
{
cout <<"Unable to open file. so Exiting from program " << endl;
return 0;
}
while(!file2.eof())
{
file2 >> value1 >> value2 >> value3 ;
cout << value1 << " " << value2 << " " << value3 << endl;
}
file2.close();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.