【问题标题】:C++ Code Creates CSV file, but does not write to itC++ 代码创建 CSV 文件,但不写入
【发布时间】:2020-08-25 06:36:42
【问题描述】:

我正在尝试学习如何将数据写入 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;
}

【问题讨论】:

  • 你需要在关闭文件之前file.flush()你的数据,因为它是临时写在内存中的,而不是在磁盘上
  • 可能路径无效或者您没有在该位置写入的权限。
  • @AlexLarionov 它应该在关闭时自动刷新。
  • OT:避免使用全局变量。这不是一个好习惯。
  • 这是一组有点奇怪的openmode 标志。试试ios::out | ios::trunc | ios::app

标签: c++ c++17 fstream iostream


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2012-11-03
    相关资源
    最近更新 更多