Finding max and min from integers in text file

Hello I have a predicament trying to read integers and placing them into an array and finding the max and min. Theres 500 of them and all separated by line:

200
300
400

My current code is this and Im pretty sure Im way off, plus the program crashing on debug isnt helping.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void analysis::i_find()
{
	ifstream input;
	input.open("input.txt");
	int x;
	while (!input.eof())
	{
		for (int i = 0; i < 500; i++)
		{
			input >> x;
			if (x > x)
				max = x;
			if (x < x)
				min = x;
			counts[x]++;
		}
		input.close();
		cout << max;
		cout << min;
	}
}


The array is also supposed to keep track of how many times a certain number is supposed to appear and Im totally lost on how to do that.
Last edited on
1
2
3
4
while (!input.eof()) {
    //...
    input.close();
}
You are trying to read from closed file.
Not to mentons that while (!input.eof()) is terribly wrong.
Also counts[x] if x is smaller than 0 or larger than counts size.

if (x > x) is always false. Perharps you meant if (x > max)
Same for min.
I hope it will help you

http://www.cplusplus.com/reference/vector/vector/
http://www.cplusplus.com/reference/algorithm/min_element/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
#include <algorithm>

int main( )
{
    // Get integer numbers
    std::vector<int> arr;
    arr.push_back( 200 );
    arr.push_back( 300 );
    arr.push_back( 800 );
    arr.push_back( 100 );
    arr.push_back( 450 );

    // Show the maximum value
    std::cout << "Maximum: " << *std::max_element( arr.begin(), arr.end() );
    std::cout << std::endl;

    // Show the minumum value
    std::cout << "Minumum: " << *std::min_element( arr.begin(), arr.end() );
    std::cout << std::endl;

    return 0;
}
Last edited on
Topic archived. No new replies allowed.