File and a while loop

Q. Consider a text file named "Data.txt" which contains an unknown number of positive integers. Write a C++ program which reads the numbers from the files and displays their total and maximum on the screen. The program should stop when one or more of the following conditions given below become true:
1. The total has exceeded 5555.
2- The end of the File has been reached.
---
I made the following code and it's giving a maximum number (80) which is correct, but it's giving a total of (5620)!!
{Entered numbers: 12 8 80}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	ifstream input("Data.txt");
	int x, max, total=0;
	while(total <= 5555)
	{
	input>>x;
	max=x;
	if(x>max)
	max=x;
	total+=x;	
	}
	cout<<"Total = "<<total<<endl;
    cout<<"Maximum is: "<<max<<endl;	
	
	return 0;
}
That it gives the correct number is just by accident because it is actully the last number. Due to line 11. Better change to

while(input>>x)

The problem of the total is that you do not care for eof and you add x to total regardless whether it would exceed the limit or not. You need an additional if befor you even set max.
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>

int main()
{
    std::ifstream input("Data.txt");

    int max = -1 ; // note: the file contains positive integers
                   //       (every value would be greater than -1)
    int total = 0 ;

    int x ;
    // loop till a. the total has not exceeded 5555 and
    //           b. an integer was successfully read from the file (end of file was not reached)
    while( total <= 5555 && input >> x )
    {
        if( max < x ) max = x ;
        total += x ;
    }

    // note: the total printed out may be greater than 5555.
    //       for example, a value of 800 was read when the total was 5400
    std::cout << "Total = " << total << '\n'
              << "Maximum is: " << max << '\n' ;
}
Thank you, it perfectly works!
Topic archived. No new replies allowed.