小编Dav*_*jko的帖子

如何在C++中保存.txt文件?

我创建了一个在 .txt 文件中编写代码并从中读取内容的代码。但是,如果我关闭程序并再次开始写入,它会删除旧文本并用新文本覆盖它。

有没有办法不覆盖现有数据?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void check() {

    string text;
    ifstream file;
    file.open("test.txt");
    getline(file, text);

    if (text == "") {
        cout << "There's no data in file" << endl;
    } else {
        cout << "File contains:" << endl;
        cout << text << endl;
    }
}

int main() {

    check();

    string text;
    ofstream file;
    file.open("test.txt");
    cout << "Type some text" << endl;
    getline(cin, text);
    file << text;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ visual-c++

2
推荐指数
1
解决办法
4万
查看次数

标签 统计

c++ ×1

visual-c++ ×1