SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Streams And File Io
Exercise:
Programming Projects
Question:2 | ISBN:9780132846813 | Edition: 5

Question

Write a program that takes its input from a file of numbers of type double and outputs the average of the numbers in the file to the screen. The file contains nothing but numbers of type double separated by blanks and/or line breaks.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#include <fstream>

#include <iostream>

#include <cstdlib>

using namespace std;

 

double get_average(ifstream&);

void output_average(double);

 

const char file_name[15] = "infile.txt";

 

int main()

{

    ifstream inStream;

 

    inStream.open(file_name);

    if (inStream.fail())

    {

        cout << "Input file opening failed. \n";

        exit(1);

    }

 

    double average = get_average(inStream);

    output_average(average);

 

    inStream.close();

 

    return 0;

}

double get_average(ifstream& instream)

{

    int index = 0;

    double next = 0, sum = 0;

 

    cout << "The numbers from the file are below." << endl;

 

    while (instream >> next)

    {

        index++;

        cout << next << " ";

        sum = sum + next;

    }

 

    cout << endl;

    return (sum/index);

}

void output_average(double average)

{

    cout.setf(ios::fixed);

    cout.setf(ios::showpoint);

    cout.precision(2);

    cout << "The average of the numbers in the file is \n"

        << average << endl;

}

 

0 0

Discussions

Post the discussion to improve the above solution.