Ask Question
7 September, 07:27

Implement the function fileSum. fileSum is passed in a name of a file. This function should open the file, sum all of the integers within this file, close the file, and then return the sum. If the file does not exist, this function should output an error message and then call the exit function to exit the program with an error value of 1.

+5
Answers (1)
  1. 7 September, 08:58
    0
    The C+ + code is given below with appropriate comments for better understanding

    Explanation:

    /*C+ + program that prompts user to enter the name of input file (input. txt in this example) and print the sum of the values in the file to console. If file dosnot exist, then close the program * /

    //header files

    #include

    #include

    #include

    #include / /needed for exit function

    using namespace std;

    //function prototype

    int fileSum (string filename);

    int main ()

    {

    string filename;

    cout << "Enter the name of the input file: ";

    cin >> filename;

    cout << "Sum: " << fileSum (filename) << endl;

    system ("pause");

    return 0;

    }

    /*The function fileSum that takes the string filename and

    count the sum of the values and returns the sum of the values*/

    int fileSum (string filename)

    {

    //Create a ifstream object

    ifstream fin;

    //Open a file

    fin. open (filename);

    //Initialize sum to zero

    int sum=0;

    //Check if file exist

    if (! fin)

    {

    cout<<"File does not exist."<
    system ("pause");

    exit (1);

    }

    else

    {

    int value;

    //read file until end of file exist

    while (fin>>value)

    {

    sum+=value;

    }

    }

    return sum;

    }//end of the fileSum
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Implement the function fileSum. fileSum is passed in a name of a file. This function should open the file, sum all of the integers within ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers