Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ coding HW: Create an input file, called file1, and an output file, called fi

ID: 3872683 • Letter: C

Question

C++ coding HW: Create an input file, called file1, and an output file, called file2, in the program. Read the data, 3 values at a time, from the input text 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 (file2) as input. Read the data back in and print it to the screen. Use a while (!file2.eof()) to control this last part. You will need a preliminary read before the while (!file2.eof()) and another read before the end of the while loop.

Run:

Create a data file of the following integers in Notepad to run the program:

10 20 30

17 21 18

30 20 49

40 25 35

55 45 35

25 55 5

-1 -1 -1

Explanation / Answer

#include<iostream>
#include<fstream>

using namespace std;

int main() {

ifstream file1;
file1.open("D:\input.txt");
ofstream file2;
file2.open ("D:\output.txt");
int n1, n2, n3;
if (file1.is_open()) {
while (!file1.eof()) {
file1>>n1>>n2>>n3;
if(n1 == -1 && n2 == -1 && n3 == -1 ) {
break;
}
if (n1 < n2 && n1 < n3) {
file2<<n1;
if(n2 < n3) {
file2 << " "<<n2<<" " <<n3<<endl;   
} else {
file2 << " "<<n3<<" " <<n2<<endl;   
}
} else if (n2 < n1 && n2 < n3) {
file2 << n2;
if(n1 < n3) {
file2 << " "<<n1<<" " <<n3<<endl;   
} else {
file2 << " "<<n3<<" " <<n1<<endl;   
}
} else {
file2 << n3;
if(n1 < n2) {
file2 << " "<<n1<<" " <<n2<<endl;   
} else {
file2 << " "<<n2<<" " <<n1<<endl;   
}
}
  
}
}
file1.close();
file2.close();
ifstream file3;
file2.open ("output.txt");
if (file3.is_open()) {
while (!file3.eof()) {
file3 >> n1 >> n2 >> n3;
cout<<n1<<" "<<n2<<" "<<n3<<endl;
}
}
file3.close();
return 0;
}

Output:

10 20 30

17 18 21

20 30 49

25 35 40

35 45 55

5 25 55

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote