[英]flag controlled loop eof loop
我正在尝试编写一个C ++程序,该程序从文件中读取数字并在屏幕上显示它们的总数和最大值。 如果满足以下一个或多个条件,则程序应停止:1.总数已超过5555。2.已达到文件末尾。 注意我必须同时使用文件结束和标志控制,同时循环才能解决此问题。
样品输入
1000 2500 1500 1100 3300 1200输出应为6100 2500
我得到的输出: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();
}
您的程序中有一个小问题。 读取的第一个数字不用于计算总和。
infile>>num; // The first number. Read and not used.
while(!infile.eof())
{
infile>>num; // The second number and subsequent numbers.
您可以使用一个while
循环而不是两个,并使用以下方法解决问题:
while( sum < 5555 && (infile >> num) )
{
if(num>=max)
max=num;
sum+=num;
}
您也不需要found
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.