0

Write a complete C++ program that reads the attached file (values.txt) to find and print the following:
a. The average value of the numbers in the file.
b. The maximum and minimum value
c. The count of negative and positive values (ignore zero)

#include <iostream>
#include<fstream>
using namespace std;
int main()
{
    int count=0,poscount=0,negcount=0;
    double avg,max=-9999999,min=9999999,num,sum=0;

        ifstream inputFile("values.txt");    // input stream to read contents of input file 

                 while(inputFile>>num)
                 {
                     sum=sum+num;
                     count++;

                    if (num>max)
                    {
                      max=num;
                    }
                        if (num<min)
                    {
                      min=num;
                    }
                        if (num>0)
                    {
                      poscount++;
                    }
                        if (num<0)
                    {
                      negcount++;
                    }
                 }

    avg=(sum/count);

    cout<<" The average value of the numbers is: "<<avg<<endl;
    cout<<" The maximum number is:               "<<max<<endl;
    cout<<" The minimum number is:               "<<min<<endl;
    cout<<" There is ( "<<poscount<<" ) positive numbers "<<endl;
    cout<<" There is ( "<<negcount<<" ) negative numbers "<<endl;
    return 0;
}

There is errors in the program but I don't know what it is not reading the numbers from the file

2
Contributors
1
Reply
11
Views
3 Years
Discussion Span
Last Post by Moschops
0

I expect it can't find the file. Is the file in the same directory that your program is running in? This is often not the same thing as the directory your source code is in.

Test that the file is found correctly.

  ifstream filestr;
  filestr.open ("test.txt");
  if (filestr.is_open())
  {
    filestr << "File successfully open";
    filestr.close();
  }
  else
  {
    cout << "Error opening file";
  }

Edited by Moschops

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.