c++ oracle 导出csv_C++ 读取和写入CSV文件

该博客展示了如何使用C++读取和写入CSV文件。通过创建一个`CSVDATA`结构体来存储数据,并利用`std::ofstream`和`std::ifstream`进行文件操作,将姓名、年龄和身高数据写入和读取到CSV文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【实例简介】

接受C 实现读取和写入文件

【实例截图】

【核心代码】

//#include

#include

#include

#include

#include // 用于读写存储在内存中的string对象

int main(void)

{

// 制作CSV文件

/* Name,age,height

* Tom,21,172.8

* John,25,189.5

*/

std::ofstream outFile;

outFile.open("./csvTest.csv", std::ios::out);

outFile << "Name" << "," << "age" << "," << "height" << std::endl;

outFile << "Tom" << "," << 21 << "," << 172.8 << std::endl;

outFile << "John" << "," << 25 << "," << 189.5 << std::endl;

outFile.close();

// 读取CSV文件

struct CSVDATA {

std::string name;

int age;

double height;

};

std::ifstream inFile("./csvTest.csv", std::ios::in);

std::string lineStr;

std::vector csvData;

std::getline(inFile, lineStr); // 跳过第一行(非数据区域)

while (std::getline(inFile, lineStr)) {

std::stringstream ss(lineStr); // string数据流化

std::string str;

struct CSVDATA csvdata;

std::getline(ss, str, ','); // 获取 Name

csvdata.name = str;

std::getline(ss, str, ','); // 获取 age

csvdata.age = std::stoi(str);

std::getline(ss, str, ','); // 获取 height

csvdata.height = std::stod(str);

csvData.push_back(csvdata);

}

// 显示读取的数据

for (int i = 0; i < csvData.size(); i ) {

std::cout << csvData[i].name << "," << csvData[i].age << "," << csvData[i].height << std::endl;

}

getchar();

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值