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

C++写入CSV文件内容失真问题求助(Code::Blocks环境)

问题原因

你的代码核心问题在于混用C语言文件操作函数和C++的std::string对象:fprintf的%s格式符要求传入const char*类型的C风格字符串,但你直接传递了std::string类对象。这会导致fprintf读取对象内存中的无效数据,最终写入CSV的内容失真。

修复方案

有两种可靠的修复方式:

方式1:转换为C风格字符串

调用std::string的c_str()方法,获取其内部的C风格字符串指针,适配fprintf的要求:

// 替换原fprintf行
fprintf(file, "%s,%s\n", name.c_str(), number.c_str());

方式2:改用C++文件流(更推荐)

完全使用C标准库的文件操作,避免C/C混合操作的兼容性问题:

#include <iostream>
#include <string>
#include <fstream> // 新增头文件
using std::cin;
using std::cout;
using std::string;
using std::endl;
using std::ofstream;

int main()
{
    string name;
    string number;
    cout << "Name: ";
    cin >> name ;
    cout << "Number: ";
    cin >> number;
    cout << name << "," << number << endl ;

    ofstream file("phonebook.csv", std::ios::app);
    if (!file.is_open())
    {
        return 1;
    }
    file << name << "," << number << endl;
    file.close();
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 22:02:32