how can I make this code work? it is supposed to read a file called numbers.txt and print out a file, output.txt. The output should have maximum and minimum which I attempted but it doesn't work. Also I need count, average and median which I did not attempt yet because I am trying to work out max and min first. However, I am running out of time for this assignment and getting quite desperate so any help you could give me would be greatly appreciated :)!
#include<fstream>
#include<cstdlib>
#include<iostream>
usingnamespace std;
int main()
{
int counter = 0;
double number, sum = 0, average, max = INT_MIN, min = INT_MAX;
ifstream read;
ofstream write;
read.open("numbers.txt");
if (read.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
write.open("output.txt");
if (write.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
while (read >> number)
{
if (number > max)
max = number;
if (number < min)
min = number;
sum = sum + number;
counter++;
}
average = sum / counter;
write << "There are " << counter << " numbers in the file numbers.dat\n";
write.setf(ios::fixed);
write.setf(ios::showpoint);
write.precision(3);
write << "The average of all numbers is " << average << endl;
write << "The maximum number is " << max << endl;
write << "The minumum number is " << min << endl;
read.close();
write.close();
}
So, what does that mean?
Maybe the files cannot be opened (especially "numbers.txt")? If so, the problem might be the relative path. The program is looking for the file at a different place than you provided the file. For test purposes you might use an absolute path.