Search code examples
c++inputfile-iosumfstream

How to replace a number in a file with its sum?


I'd like to write a program that gets an integer in a file, sums it with a input number and replace the previous integer in the file with the result of the sum. I thought the following code would work, but there's a 0 written in the file that remains 0, no matter the integer I input. What am I doing wrong?

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    fstream arq;
    arq.open("file.txt");
    int points, total_points;
    cin >> points;

    arq >> total_points;
    total_points += points;
    arq << total_points; 
        
}

Solution

  • You can try reading and writing the input file separately as shown below:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        ifstream arq("file.txt");
        int points=0, total_points=0;
        cin >> points;
    
        arq >> total_points;
       
        total_points += points;
        arq.close();
        ofstream output("file.txt");
        
        output  << total_points;
        output.close();
        
            
    }
    

    The output of the above program can be seen here.