from file to array then finding lowest number.

It reads the numbers from a file but it is then supposed to find the lowest number. Right now it seems to read numbers from a file (txt file) but it seems to only be reading the first number and printing that. When it should be reading them all and finding the lowest number.
Not sure what I'm missing here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<fstream>
#include<cstdlib>
#include <climits>

using namespace std;


int main() {


	cout << "I will pull the numbers from test.txt. put them in an array, and then print the smallest number. \n";
	 ifstream instream;

	int file_numbers[100]; // name of the array

	instream.open("test.txt");
	 if (instream.fail()) {
		 cout << "Faild to open file! \n";
		 exit(1);
	 }

	 int cnt = 0;  // this will be a counter into the array

	while (instream >> file_numbers[cnt]) {
		// the while loop is pretty short because it just reads into the array

		cnt++;
	}

	int smallest =  INT_MAX ;  // if you start it at max int, you will get the smallest at the end
	 for ( int i=0; i < cnt; ++i ) { // go from 0 to cnt

		if ( file_numbers[i] < smallest )
			  smallest = file_numbers[i] ;
	 }
	cout << smallest << '\n' ;

	return(0);
}
I do not understand that silly phrase "it seems to only be reading the first number "

Do you have some problems to output the value of cnt that to see how many records were read?
Last edited on
In the test.txt that I'm using to pull the numbers from whatever I change the first number to is the one it prints out. If the fist number is 78 that is the one that prints out.
I don't understand what you mean by "output the value of cnt that to see how many records were read?"
he is telling to print the cnt, to see how many items you read from the file. You can also print the array
I din't know you could do that. When I do a cout with cnt I get 6 and a cout with the array gives 0x7fff9a0bcba0.
So you read 6 elements. What is the problem?
try to print the contents of array(file_numbers)..
Is an element each number in the file? It's supposed to read them all and print the lowest one. Right now it only prints the first number.
I see now from printing the cnt that it is reading all the numbers, so my error must be in how it is sorting or supposed to be sorting the numbers.
Your function is correct except that the number of read elements can exceed 100.
So the function should output the correct smallest number.
Last edited on
Okay it's working thank you for the help.
Topic archived. No new replies allowed.