C++ realizes the read and write function of csv files (can be used directly)

create a header file

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


int csvTest();

int readCsv();

Create the corresponding cpp file

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

using namespace std;


//Output the data in the form of csv
int csvTest() {     ofstream p;     p.open("output.csv", ios::out | ios::trunc); //Open file path     p << "Student Number" << "," << "Name" << "," << "Total Score" << "," << "Rank" << endl; //Enter content, pay attention to use commas to separate     p << "010101" << "," << "Zhang San" << "," << "98" << "," << "1" << endl; p << "010102" << ","     < < "Li Si" << "," << "88" << "," << "2" << endl;




    p.close();

    return 0;
}


//Read the data of the csv file and encapsulate it into a string
int readCsv() {     std::ostringstream oss;

    // read the file
    ifstream inFile("output.csv", ios::in);
    string lineStr;
    vector<vector<string>> strArray;
    while (getline(inFile, lineStr))
    {         // print the whole line of string         cout < < lineStr << endl;         //write output stream         oss << lineStr << "\n";     }     std::string s = oss.str();     cout << s << endl;






    return 0;
}
 

The io operation of c++ is relatively simple and very practical;

Guess you like

Origin blog.csdn.net/weixin_45533131/article/details/130468044