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

C++中使用FILE将string写入TXT文件出现乱码如何解决?

问题修复方案

你的代码问题在于fprintf的%s格式符要求传入C风格字符串指针(const char*),但你直接传递了std::string对象,这会导致fprintf错误地解析std::string内部的内存结构,从而输出乱码。

修复方法很简单,调用std::string的c_str()方法获取其内部的C风格字符串指针:

FILE *outfile = fopen("solution.txt", "w");
std::string test = "6.5.1";
fprintf(outfile, "%s\n", test.c_str());
// 务必关闭文件,避免资源泄漏和数据写入不完整
fclose(outfile);

补充说明

  • std::string::c_str()会返回一个指向字符串首字符的const char*,完全匹配%s的参数要求。
  • 如果你后续有优化空间,也可以考虑使用C++标准库的std::ofstream,它原生支持std::string,代码更简洁安全:
    #include <fstream>
    #include <string>
    
    int main() {
        std::ofstream outfile("solution.txt");
        std::string test = "6.5.1";
        outfile << test << '\n';
        return 0;
    }
    
    不过既然你需要传递FILE*作为参数,第一种修复方式更贴合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:01:11