gpt4 book ai didi

c++ - 如何读取没有换行符 CRLF "\r\n"的 CSV 记录?

转载 作者:太空狗 更新时间:2023-10-29 21:02:58 28 4
gpt4 key购买 nike

我是 C++ 的新手,我一直在尝试弄清楚如何将 CSV 文件读入 vector 。到目前为止一切都很好,除了我不知道如何避免每条 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

最佳答案

尝试:

while (std::getline(ss, field, ';'))
{
// add the converted field to the end of the record
record.push_back(field.erase(s.find('\r'));
}
//record.push_back(field.erase(s.find('\r'));
return ins;

关于c++ - 如何读取没有换行符 CRLF "\r\n"的 CSV 记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14229590/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com