c++ 对csv文件的读写功能实现(可以直接用)

创建一个头文件

#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int csvTest();

int readCsv();

创建对应的cpp文件

#include "csvTest.h"
#include <vector>
#include <sstream>

using namespace std;


//将数据以csv的形式输出
int csvTest() {
    ofstream p;
    p.open("output.csv", ios::out | ios::trunc);                //打开文件路径
    p << "学号" << "," << "名字" << "," << "总分" << "," << "名次" << endl;    //输入内容,注意要用逗号,隔开
    p << "010101" << "," << "张三" << "," << "98" << "," << "1" << endl;
    p << "010102" << "," << "李四" << "," << "88" << "," << "2" << endl;

    p.close();

    return 0;
}


//读取csv文件的数据,并封装成字符串
int readCsv() {
    std::ostringstream oss;

    // 读文件
    ifstream inFile("output.csv", ios::in);
    string lineStr;
    vector<vector<string>> strArray;
    while (getline(inFile, lineStr))
    {
        // 打印整行字符串
        cout << lineStr << endl;
        //写入输出流
        oss << lineStr << "\n";
    }
    std::string s = oss.str();
    cout << s << endl;

    return 0;
}
 

c++的io操作时比较简单的,非常的实用;

猜你喜欢

转载自blog.csdn.net/weixin_45533131/article/details/130468044