C ++代码创建CSV文件,但未写入它

问题描述 投票:0回答:1

我正在尝试学习如何将数据写入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++17 fstream iostream
1个回答
0
投票

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

#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;
}

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

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

© www.soinside.com 2019 - 2024. All rights reserved.