← Back to Streams
Question 578
Sum Numbers in a File
Sum Numbers in a File
A text file contains whole numbers separated by spaces or newlines, for example: 10 20 30 Write a functionint sumFile(const string& filename)that returns the sum of every number in the file. The starter opens the file and already loops withwhile (in >> n); add the line inside the loop that addsntototal. Numbers may be negative and several may share one line. The test prints the returned sum on its own line, for example (see Expected Output). Do NOT write a main function.
Expected Output:
60 11
= newline. The output ends with a newline — print one after the last line.
Hints2 available
Sign in to use hintsTopics:
Streamsifstream
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.