首页 > 解决方案 > C++ 代码创建 CSV 文件,但不写入

问题描述

我正在尝试学习如何将数据写入 C++ 中的文件,在本例中为 CSV 文件。目前我的代码将在我选择的位置创建文件,但是当我打开文件时,它是一个空白文档。这里的任何见解将不胜感激!谢谢你。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


const char *path = "/Users/eitangerson/desktop/Finance/ex2.csv";
ofstream file(path);
//string filename = "ex2.csv";




int main(int argc, const char * argv[]) {
    file.open(path,ios::out | ios::app);
    file <<"A ,"<<"B ,"<< "C"<<flush;
    file<< "A,B,C\n";
    file<<"1,2,3";
    file << "1,2,3.456\n";
    file.close();



    return 0;
}

标签: c++c++17fstreamiostream

解决方案


我能够通过声明文件对象而不是初始化它来使其工作。看一看:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


const char* path = "ex2.csv";
ofstream file;

//string filename = "ex2.csv";


int main(int argc, const char* argv[]) {
    file.open(path, ios::in | ios::app);
    file << "A ," << "B ," << "C" << flush;
    file << "A,B,C\n";
    file << "1,2,3";
    file << "1,2,3.456\n";
    file.close();

    return 0;
}

所以你在正确的道路上。我还建议您不要使用全局变量。除此之外,你应该很高兴!

编辑:我在我的版本中更改了路径,所以我可以在项目文件夹中输入单词。


推荐阅读