Reading integers from file and displaying high and low numbers.

closed account (jhb7Djzh)
I need to have my program read each integer for a file called "integers.dat" and at the end, display the highest and lowest number. No matter what I change it seems to display the same numbers which are in the millions range even though all my integers are single or double digits. The file is in the same directory as the program.

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
  #include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main(){

ifstream fin; //declaring stream variable
fin.open("integers.dat"); //connecting to file
int num, high, low;
high=0;
low=0;
while(!fin.eof()){
	fin >> num;
	if(num>high){
		high=num;
	}else if(num<low){
	low=num;
	}else{
		continue;}
}
fin.close();
cout<<"High number: "<<high<<"\nLow number: "<<low<<endl;
return 0;
}
Last edited on
high is set to a million billion billion at the start, isn't it? Is it? If you think it isn't, what do you think the initial value of high is?
closed account (jhb7Djzh)
I initialized high and low to be 0 at the start. Now high is the same but low is 0
So at the beginning low is zero, and then you enter some other numbers, all of which are above zero?

So when would the value of low be changed? Did you enter a number less than zero? Why did you set low to zero at the start, if all the number you enter are greater than zero?

closed account (jhb7Djzh)
Yeah I see what you're saying, I don't know why I did that.

So if I get the first int of the file and assign it to both high and low variables, that will give me a reference to compare the rest of the integers with.

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
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main(){

ifstream fin; //declaring stream variable
fin.open("integers.dat"); //connecting to file
int num, high, low;
fin >> num; //assign first int
	num=high; 
	num=low; //assigning first int to high and low as a reference
while(!fin.eof()){
	fin >> num; //assign next int
	if(num>high){
		high=num;
	}else if(num<low){
	low=num;
	}else{
		continue;}
}
fin.close();
cout<<"High number: "<<high<<"\nLow number: "<<low<<endl;
}

Topic archived. No new replies allowed.