簡體   English   中英

標志控制循環eof循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM