Home > Blockchain >  How to replace a number in a file with its sum?
How to replace a number in a file with its sum?

Time:12-08

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; 
        
}

CodePudding user response:

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.

CodePudding user response:

Since you've opened the file for both reading and writing you need to set the output position indicator to position 0 before you write the new value to the file.

Example:

#include <cerrno>
#include <fstream>
#include <iostream>

int main() {
    const char* filename = "file.txt";
    if(std::fstream arq(filename); arq) {
        if(int total_points; arq >> total_points) {
            if(int points; std::cin >> points) {
                total_points  = points;
                // rewind the output position pointer to the start of the file
                arq.seekp(0);
                arq << total_points;
            }
        }
    } else {
        std::perror(filename);
    }
}

Note though that if you want to write a shorter value to the file, you may end up with a file looking like this:

Before:

123456

After writing 45 to the file:

453456

So, I recommend the approach in Anoop Rana's answer which truncates the file before writing to it.

  • Related