Exercise #3: Write a c++ program that reads, from a file called numbers.in, up to 10 numbers, counts and adds the positive values and then displays the results. Your program should terminate whenever it either reads 10 numbers or a negative number. Assume at least there is one number in the file.​

Respuesta :

I don't know

Thanks for the points

Answer:

We should read the file number numbers. in and add up to 10 positive numbers or until there is a negative number.

Explanation:

#include <iostream>

#include <fstream>

using namespace std;

int main()

{   int sum=0,count=0; //Variables for storing sum and counts of positive numbers

   string filename("numbers.in"); //Name of the file to read from

   int number; //The numbers in the file

   ifstream input_file(filename);

   if (!input_file.is_open()) {

       cerr << "Could not open the file - '"<< filename << "'" << endl;//If file could not be opened, displaying error message

       return EXIT_FAILURE; //Returning unsuccessful termination

   }

   while (input_file >> number) //Reading all numbers from file

       {

           if(number>0 && count<10) //If number is is a positive number and it is not the 11th or greater element of file

               {

                   sum+=number; //Adding numbers

                   count++; //Increasing the count

               }

           else //Otherwise we will break out of the loop

               {

                   break;

               }

   }

   if(count<10) //If count is less than 10, then displaying an appropriate message on the console

       {

           cout<<"There are " <<count<<" positive numbers"<<endl<<"The sum of the positive numbers is: "<<sum<<endl;

       }

   else //Otherwise there were more than 10 positive number, then displaying an appropriate message on the console

       {

           cout<<"There are at least " <<count<<" positive numbers"<<endl<<"The sum of the positive numbers is: "<<sum<<endl;

       }

   input_file.close(); //Closing file

   return EXIT_SUCCESS; //indicates successful program execution status

}

ACCESS MORE