Prompt the user for the name of an input file. Open and read the first line of t
ID: 662569 • Letter: P
Question
Prompt the user for the name of an input file. Open and read the first line of this user-specified input file. Create a double array with a size to match the first line of the input file. So this means that if the first line of the input file is a 100, the array will have 100 slots. If the first line of the input file is a 200, the array will have 200 slots. This means that the array must be dynamically sized according to the first line read from the file. Your program should then read the remaining numbers into the array. Once the array has been filled, sort the array from low to high. After the sort is complete, use a loop to sum the elements in the array, and then calculate the average of all values within the array. Prompt the user for the name of an output file. Open this user-specified output file and write the following information to this file: the number of slots in the array, followed by the sorted list of numbers (one per line), and finally, the average value within the array. Use the provided scores.dat test data file to get your program working.
Explanation / Answer
The following code can be used to read a file into an array :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array_size = 1024; // define the size of character array
char * array = new char[array_size]; // allocating an array of 1kb
int position = 0; //this will be used incremently to fill characters in the array
string ext;
cout << "Enter the file location" << endl;
getline(cin,ext)
ifstream fin("C:\Users\Cherime\Desktop\test.txt"); //opening an input stream for file test.txt
/*checking whether file could be opened or not. If file does not exist or don't have read permissions, file
stream could not be opened.*/
if(fin.is_open())
{
//file opened successfully so we are here
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
//this loop run until end of file (eof) does not occur
while(!fin.eof() && position < array_size)
{
fin.get(array[position]); //reading one character from file to array
position++;
}
array[position-1] = ''; //placing character array terminating character
cout << "Displaying Array..." << endl << endl;
//this loop display all the charaters in array till
for(int i = 0; array[i] != ''; i++)
{
cout << array[i];
}
}
else //file could not be opened
{
cout << "File could not be opened." << endl;
}
return 0;
}
And as for the sorting of the numbers a function can be used. the following function can be used to sort the numbers :
while( !inFile.eof() && i < size)
{
inFile >> tmp;
iArray[i] = tmp;
j = i;
while (j > 0 && iArray[j-1] > iArray[j])
{
swap(iArray[j], iArray[j-1]);
j--;
}
i++;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.