The goal of my program is to eventually read a file filled with numbers (chosen by the user) into an array and to output the min and max values. However, I cannot get my code to output the correct number of inputs in the file, which I want to use as the size of my array.
The code I have now is
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
string fileName;
int count(0);
cout << "Enter input file name: ";
cin >> fileName;
ifstream in_file;
in_file.open(fileName);
if(in_file.is_open()){
in_file >> count;
}
cout << "The number of entries is " << count;
int arrayNumbers[count];
for (int i = 0; i < count; ++i){
in_file >> arrayNumbers[i];
cout << arrayNumbers[i] << endl;
}
in_file.close();
}
I have a text file called tester.txt in the same directory as my .cpp file, but it only has 9 entries (1-9 on seperate lines) yet when I cout the count, it says the count is 12. I have seen in other questions like mine the use of
in_file >> count;
to count how many numbers are in a file, but I don't understand what this does since its my first time reading from a file. The file I am trying to read from has the following in it
1
2
3
4
5
6
7
8
9
I have not started the second part of the problem, finding the min and max, however I was just going to sort the array and then display arrayNumber[0] and arrayNumber[count-1] to show the min and max, but first I need to know how large to make the array based on the input file.