C++ reads and writes pure data CSV files

CSV file

CSV (Comma Separated Values) is a plain text file format used to store tabular data such as spreadsheets or databases. It essentially stores tabular data including numbers and plain text. Most online services give users the freedom to export data from websites into CSV file format. CSV files will usually be opened in Excel, and almost all databases have different specific tools to allow the same to be imported. So C++ can handle CSV files very conveniently

CPP read pure data csv file

Since there is only data in the project csv file, only the reading code is written. If there are other characters, just modify the storage type.
Source code:

#include <iostream> 
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
// 统计一行元素个数
int getLong(string line) {
    
    
    int numsize = 0;
    for (auto a : line)
        if (a == ',') numsize++;
    return numsize + 1;
}
// 主函数入口
vector<vector<double>> csvRead(string filename)
{
    
    
	vector<vector<double>> result;
	ifstream infile(filename, ios::in);
	string line;
	getline(infile, line);
	int sizex = getLong(line);
	while (getline(infile, line)) {
    
    
		stringstream ss(line);
		string str;
		vector<double> lineReader;
		for (int i = 0; i < sizex; i++) {
    
    
			getline(ss, str, ',');
			lineReader.push_back(stod(str));
		}
		result.push_back(lineReader);
	}
	return result;
}

CPP write CSV file

Since the code is relatively simple, I will not introduce too much
source code

bool csvWrite(vector<vector<double>> data, string output_filename)
{
    
    
	ofstream outFile(output_filename, ios::out);
    if (!outFile)
    {
    
    
        // out part
        cout << "打开文件失败!" << endl;

        return false;
    }
    for (auto i : data) {
    
    
        for (auto j : i) {
    
    
            outFile << j << ",";
        }
        outFile << endl;
    }
    outFile.close();
	return true;
}

Guess you like

Origin blog.csdn.net/weixin_51717597/article/details/126610245