2017-07-06 143 views
-3
#include<iostream> 
#include<fstream> 
using namespace std; 
string dataFile = "data.txt"; 
int counter; 

int main() 
{ 
    string input =""; 
    fstream data; 
    data.open(dataFile, ios::app | ios::out | ios::in); 
    getline(data, input); 
    if (input == "")//The file must be new 
    { 
     counter = 0; 
    }else { 
     counter = stoi(input); 
    } 

    /* 
     Program does some stuff that increases the counter 
     Right before program ends we update the file 
    */ 
    data.clear(); 
    data << counter; 
    data.close(); 
    return 0; 
} 

所以這只是一些示例代碼。第一次運行程序時,計數器從0開始,這是準確的。假設你在比賽中得到10分。當遊戲結束時,你的計數器將是10,並且它被存入文件沒問題。所以讓我們重新打開應用程序,你會發現計數器是10,很酷,而且你這次獲得6分。所以在遊戲中,計數器讀數爲16.在應用程序關閉之前,將16寫入data.txt。C++如何覆蓋C++中的文本文件中的數據?

裏面的data.txt它讀取1016,這是不準確的!

在我將準確的計數器信息寫入文件之前,如何清除data.txt中的文本?

我在其他地方讀過,你無法使用fstream清除文件的內容,有沒有更有效的方法來覆蓋文件中的數據?

謝謝。

+0

請參考[tour](https://stackoverflow.com/tour)並閱讀[help](https://stackoverflow.com/help)頁面。 – Ron

回答

2

將文件讀入內存。更新值。重寫該文件。