← Back to Streams
Question 656
Write Then Read in One Object
Write Then Read in One Object
Write a functionint writeAndSum(const string& filename, const vector<int>& v)that uses ONEfstreamobject for both directions: 1. Openfilenameinios::in | ios::out | ios::truncmode. 2. Write every number invto the file separated by single spaces, followed by a newline. 3. Move the read position back to the start withseekg(0). 4. Read the numbers back from the file with>>until reading fails, adding them up as you go. 5. Return the sum you read from the file. The test prints the returned sum on its own line. Forv = {1, 2, 3, 4, 5}it prints the output shown in Expected Output. Do NOT write a main function.
Expected Output:
15 12
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
Streamsfstream
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.