So I was given the assignment that asks user to enter file name, then the program will read all integers from the file (unknown number of integers) to an array, and display highest, lowest number, average and number of integers read.
The only problem that I have with this is right at the beginning. To check whether user enters a correct file name, I use a while loop. But it turned out that even if user enters a correct file name at the second time (given the first time he fails), he still cannot quit the loop.
Any idea where the bug is?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
const int SIZE = 400;
int actual_size = 0, number[SIZE], highest, lowest, sum;
double average;;
ifstream inputfile;
string file_name;
cout << "Please enter a file name: ";
cin >> file_name; // get file name from user
inputfile.open(file_name.c_str()); // open file, using the file name user entered
// check if opening file succeeds. if not ask user to submit a right name
while (!(inputfile))
{
cout << "\nError. Please enter a correct file name: ";
cin >> file_name;
inputfile.open(file_name.c_str());
} // end while-statement
// read inputfile into array number - actual_size = 0 at the beginning
while (inputfile >> number[actual_size])
actual_size++;
// end while-statement
// find lowest and highest number, and sum
sum = number[0];
lowest = number[0];
highest = number[0];
for (int index = 1; index < actual_size; index++)
{
sum += number[index];
if (number[index] >= highest)
highest = number[index];
if (number[index] <= lowest)
lowest = number[index];
} // end for-statement.
average = 1.0 * sum / actual_size; // calculating average
cout << fixed << showpoint << setprecision(2);
cout << "The highest number is: " << highest
<< "\nThe lowest number is: " << lowest
<< "\nThe total of the numbers in the array is: " << actual_size
<< "\nThe average of the numbers in the array is: " << average << endl;
return 0;
} // end function main
This is the file that I used "test.txt"
100
200
300
400
50
60
0
80
90
350