我对 C++ 非常陌生,我一直在试图弄清楚如何将 CSV 文件读入向量。到目前为止一切都很好,除了我不知道如何避免在每条 CSV 记录的末尾换行。
这是我的代码:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
// stream input operator overloaded to read a list of CSV fields
std::istream &operator >> (std::istream &ins, std::vector<std::string> &record)
{
record.clear();
// read the entire line into a string
std::string line;
std::getline(ins, line);
// using a stringstream to separate the fields out of the line
std::stringstream ss(line);
std::string field;
while (std::getline(ss, field, ';'))
{
// add the converted field to the end of the record
record.push_back(field);
}
return ins;
}
// stream input operator overloaded to read a list of CSV fields
std::istream &operator >> (std::istream &ins, std::vector<std::vector<std::string>> &data)
{
data.clear();
// add results from record into data
std::vector<std::string> record;
bool empty;
while (ins >> record)
{
// check if line has a price
for (unsigned i = 0; i < record.size(); i++)
{
std::stringstream ss(record[2]);
int price;
if (ss >> price)
{
empty = true;
}
else
{
empty = false;
}
}
if (empty == true)
{
data.push_back(record);
}
}
return ins;
}
int main()
{
// bidemensional vector for storing the menu
std::vector<std::vector<std::string>> data;
// reading file into data
std::ifstream infile("test.csv");
infile >> data;
// complain if theres an error
if (!infile.eof())
{
std::cout << "File does not excist." << std::endl;
return 1;
}
infile.close();
for (unsigned m = 0; m < data.size(); m++)
{
for (unsigned n = 0; n < data[m].size(); n++)
{
std::string recordQry;
recordQry += "'" + data[m][n] + "', ";
std::cout << recordQry;
}
std::cout << std::endl;
}
return 0;
}
test.csv 包含:
CODE;OMSCHRIJVING; PRIJS ;EXTRA;SECTION
A1;Nasi of Bami a la China Garden; 12,00 ;ja;4
A2;Tjap Tjoy a la China Garden; 12,00 ;ja;1
A3;Tja Ka Fu voor twee personen; 22,50 ;ja;1