In: Computer Science
Objectives
To learn to code, compile, and run a program using file input and an output file.
Assignment
Plan and code a program utilizing one file for input and one file for output to solve the following problem:
Write a program to determine the highest number, the lowest number, their total, and the average of each line of numbers in a file. A file contains 7 numbers per line. How many lines a file contains is unknown.
Note
Label all output clearly. Be sure your output file contains user prompts and what was entered by the user in addition to the results of your program processing. Be sure your output file contains data that was input in addition to the results of your program processing. Create the data file below using your text editor or Notepad. Copying and pasting the numbers might create problems with reading from the files. Type in the numbers. Separate numbers by using either the tab key or blank spaces.
Data File Sample
346 130 982 90 656 117 595
415 948 126 4 558 571 87
42 360 412 721 463 47 119
441 190 985 214 509 2 571
77 81 681 651 995 93 74
310 9 995 561 92 14 288
466 664 892 8 766 34 639
151 64 98 813 67 834 369
Here is the code for the given problem :-
#include<iostream.h>
#include<fstream.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
std::ifstream fin("input.txt");
int val=0, rows=0, cols=0, numItems=0;
ofstream myfile;
myfile.open ("output.txt");
while( fin.peek() != '\n' && fin >> val )
{
myfile << val << ' ';
++numItems;
}
cols = numItems;// # no of columns =7
myfile << '\n';
while( fin >> val )
{
++numItems;
myfile << val << ' ';
if( numItems%cols == 0 ) cout << '\n';
}
if( numItems > 0 )// got data!
{
rows = numItems/cols;
myfile << "rows = " << rows << ", cols = " << cols << '\n';
}
else// didn't get any data
myfile << "data reading failed\n";
vector<vector<<int>> matrix;
while(row!=0)
{
vector<int> a;
int sum=0
while( fin.peek() != '\n' && fin >> val )
{
sum+=val;
a.push_back(val);
}
myfile << "\nMax Element of this line = "
<< *max_element(a.begin(), a.end());
myfile << "\nMin Element of this line = "
<< *min_element(a.begin(), a.end());
myfile<<"\nAverage of the elements of this line = "
<< sum/7;
row--;
}
myfile.close();
return 0;
}
Here we read the file "input.txt" using ifstream fin, and writes the data present in it along with max element, min element, and the average of each line in another file "output.txt" and then close the file.
Hope this helps :) Feel free to ask any doubt in the comment section.