如何读取文件然后在打开文件时写入文件?

How to read a file and then write to it with one open?

我有一个文本文件,里面只有一个数字。

我想打开文件并读取数字,然后我想从控制台输入一个新数字。然后将之前的数字和输入的数字相加。例如,文件中已有的数字是5,那么我输入10,我想将15写入文件并再次循环。我的代码如下:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
    string s;
    cout << "Please enter a new number" << endl;
    while (getline(cin, s)) {
        if (s.empty()) {
            break;
        }
        fstream ff;
        string pre;
        ff.open("file.txt", ios::out | ios::in);
        if (ff.is_open()) {
            // read the pre number
            getline(ff, pre);
            cout << "Pre number: " << pre << endl;
            // Write new number
            int new_number = stoi(pre) + stoi(s);
            ff << new_number << endl;
            // Read the new number
            ff.seekg(ios::beg);
            getline(ff, pre);
            cout << "New number: " << pre << endl;


        }
        ff.close();
    }
    return 0;

问题是无法将输入的数字写入文件。始终存在文件中的数字。

Please enter a new number
12
Pre number: 78
New number: 78
12
Pre number: 78
New number: 78
12
Pre number: 78
New number: 78

谁能给我提示?

您应该使用 std::ostream::seekg to set ostream to point to the new location set by istream and also use std::ostream::seekp 设置 istream 指向 ostream 设置的新位置。

您还可以使用 std::fopenr+,a+ 标志,以便 read/write 归档。