cpp创建csv格式文件
时间: 2023-05-23 11:04:20 浏览: 60
A:可以使用文件操作和字符串流来创建CSV格式文件。具体操作如下:
1. 包含头文件
```cpp
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
```
2. 定义CSVWriter类
```cpp
class CSVWriter
{
public:
CSVWriter(std::string filename, std::string delm = ",") :
fileName(filename), delimiter(delm), lines({}) {}
void addLine(std::vector<std::string> values);
void writeToFile();
private:
std::string fileName;
std::string delimiter;
std::vector<std::string> lines;
};
```
3. 实现CSVWriter类的方法
```cpp
void CSVWriter::addLine(std::vector<std::string> values)
{
std::stringstream ss;
for (size_t i = 0; i < values.size(); i++)
{
if (i != 0)
ss << delimiter;
ss << "\"" << values[i] << "\"";
}
lines.push_back(ss.str());
}
void CSVWriter::writeToFile()
{
std::ofstream file(fileName);
for (const auto& line : lines)
{
file << line << "\n";
}
file.close();
}
```
4. 使用CSVWriter类来创建CSV文件
```cpp
int main()
{
CSVWriter writer("test.csv"); // 创建名为"test.csv"的文件
std::vector<std::string> line1 = {"ID", "Name", "Age"}; // 第一行
writer.addLine(line1);
std::vector<std::string> line2 = {"1", "Tom", "20"}; // 第二行
writer.addLine(line2);
std::vector<std::string> line3 = {"2", "Mary", "25"}; // 第三行
writer.addLine(line3);
writer.writeToFile(); // 写入文件
return 0;
}
```
运行后,会在当前目录下生成名为"test.csv"的文件,并且文件内容如下:
```
"ID","Name","Age"
"1","Tom","20"
"2","Mary","25"
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)