c++ - 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;
}
解决方案
我能够通过声明文件对象而不是初始化它来使其工作。看一看:
#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;
}
所以你在正确的道路上。我还建议您不要使用全局变量。除此之外,你应该很高兴!
编辑:我在我的版本中更改了路径,所以我可以在项目文件夹中输入单词。
推荐阅读
- django - 如何访问 djongo 模型上的 _id 字段,它返回无
- javascript - 重定向到 PHP 中的另一个页面
- python - 我可以在 py spark 中读取本地文件,但无法在本地文件中写入数据帧
- algorithm - 通过邻域中的样本计算 3D 点的法线
- ruby-on-rails - Ruby on Rails - 按 created_at 和 sort_by 按布尔排序记录
- kotlin - Android Appium 摄像头测试:如何像来自摄像头一样注入视频以使用 Appium 测试应用程序
- php - 使用exif压缩后如何在上传时更改图像方向 - PHP
- python - 使用 python openpyxl 检查重复值和输入值
- arrays - 在 VBA 中使用命名范围
- reactjs - 当我没有验证时,为什么我的 Formik 表单没有提交?