I am trying to write a C++ program which reads numbers from a file and display their total and maximum on the screen. The program should stop if one or more of the conditions given below become true: 1. The total has exceeded 5555. 2. The end of file has been reached. Note I MUST use both end-of-file and flag control while loops to solve this problem.
SAMPLE INPUT
1000 2500 1500 1100 3300 1200the output should be 6100 2500
the output i get : 7500 2500
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
int num;
int sum=0;
int max=0;
bool found=false;
infile.open("Input.txt");
outfile.open("output.txt");
if(!infile)
cout<<"File Can not open \n";
else
{
infile>>num;
while(!infile.eof())
{
infile>>num;
while(!found)
{
if(num>=max)
max=num;
sum+=num;
if(sum>=5555)
found=true;
}
}
}
outfile<<sum<<endl;
outfile<<max<<endl;
infile.close();
outfile.close();
}
You have a small problem in your program. The first number being read is not used to compute the sum.
infile>>num; // The first number. Read and not used.
while(!infile.eof())
{
infile>>num; // The second number and subsequent numbers.
You can use one while
loop instead of two and fix the problem also by using:
while( sum < 5555 && (infile >> num) )
{
if(num>=max)
max=num;
sum+=num;
}
You don't need the found
variable either.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.