You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++写入文件内容消失问题求助:期望追加多行用户名

问题根源

你用ofstream file(path);打开文件时,默认启用的是截断模式(ios::trunc)——这种模式会直接清空文件原有内容,再写入新数据,所以每次运行程序都会覆盖之前的内容。

解决办法

要实现追加写入,只需在打开文件时指定追加模式,通过ios::app标志即可(也可以用ios::out | ios::app,显式声明输出+追加)。

修改后的完整代码:

#include <iostream>
#include <fstream>
#include <cstdlib> // 引入exit()所需的头文件

using namespace std;

int main(){
    string username = "";
    string path = "/Users/kishorejyothi/Desktop/C++/practice/list_usernames.txt";
    // 打开文件时指定追加模式
    ofstream file(path, ios::app);

    if(file.fail()){
        cerr << "Failed process";
        exit(1);
    }

    cout << "Enter a username: ";
    cin >> username;

    // 直接构造完整用户名,避免修改原username变量
    string full_username = username + "@Abhinav.com";

    if(username.empty()){
        cout << "You didn't enter your username";
    }
    else{
        cout << "Thanks for entering your preferred username." << endl;
        cout << "Your username is now " << full_username;
        // 仅在输入有效时写入文件,避免无效内容追加
        file << full_username << endl;
    }

    file.close();
    return 0; // 符合C++标准,返回0表示程序正常结束
}
额外优化说明
  • ios::app模式会自动将写入位置定位到文件末尾,新内容会追加在已有内容之后,不会覆盖原有数据。
  • 原代码中username.append("@Abhinav.com")会直接修改username的值,改成直接构造full_username更清晰,也避免了原变量被意外修改。
  • 补充#include <cstdlib>,因为exit()函数需要这个头文件支持(部分编译器可能隐式包含,但显式引入更规范)。
  • 调整写入逻辑:只有当用户输入了有效用户名时才写入文件,避免空行或无效内容被追加到文件中。
  • 给main函数添加return 0;,符合C++标准规范。

内容的提问来源于stack exchange,提问作者EdwardTheTrain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 00:12:40