Accessing a .txt file and finding the number closest to 200

Hi, in this program I am to open a .txt file and find the integer that is closest to 200.The code is working;however, the results is either giving me the last or the first number in the sequence.The numbers in the .txt files is...
55 67 458 23 81 33 782 375 528 405 324 950 46 14 864 551 38 167 518 630
Any help to improve the following code would be greatly appreciated.
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
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>

using namespace std;

void main() {

	int num,closest,sum;
	ifstream Filein;
	ofstream Fileout;
	Filein.open("F:\\Datafile2.txt");
	Fileout.open("F:\\ANSWERS.txt");
	//TaskF
	Filein >> num;
	while(Filein){
		sum = abs(num - 200);
		if (sum < num) {
			closest = num;
		}
		else if (sum > num) {
			closest = num;
		}
		Filein >> num;
	}
	Fileout << "The number closest to 200 is: " << closest << endl;
	Filein.close();
	Filein.clear();

}
your error is that either it is < or > you assign the closest with the number, it does not make sense. Simply remove the else if and put the line 25 before the line 18;
That worked, thanks for the quick response.
welcome
Topic archived. No new replies allowed.