如何修复此"terminate called after throwing an instance of 'std::out_of_range"错误?



我尝试读取一些csv数据,但我一直得到这个错误:

抛出'std::out_of_range'实例后调用终止
what(): vector::_M_range_check: __n(为1)>= this->size()(即1)

customer.csv

id, name, address
1, "Knut", "Knutveien 3"
2, "Lise", "Liseveien 7"

main.cpp

#include <iostream>
#include "rapidcsv/rapidcsv.h"
using namespace std;
void read_customer()
{
rapidcsv::SeparatorParams sp; // make a object sp
sp.mTrim = true; // remove the line space, equal to true
// open the customer document
rapidcsv::Document doc_customer("customers.csv", rapidcsv::LabelParams(), sp);
for (int i = 0; i < doc_customer.GetRowCount(); i++)
{
auto name = doc_customer.GetCell<string>("name", i);
auto address = doc_customer.GetCell<string>("address", i);
cout << "customer: " << name << ", " << address << endl;
}
}
int main()
{
read_customer();
return 0;
}

输入数据看起来不像常规的CSV数据。如果您从数据中删除空行,并将其更改为如下内容:

id, name, address
1, "Knut", "Knutveien 3"
2, "Lise", "Liseveien 7"

在尝试读取之前,rapidcsv能够正确解析它。

c++代码看起来不错,除了使用不同的文件名customers.csv,而不是在问题(customer.csv)中指定。

为了完整起见,我从customer.csv中删除了空白行,并使用了以下成功解析文件的main.cpp内容。

#include <iostream>
#include <vector>
#include "rapidcsv.h"
void read_customer()
{
rapidcsv:: SeparatorParams sp; // make a object sp
sp.mTrim = true;  //remove the line space, equal to true
// open the customer document
rapidcsv:: Document doc_customer("customer.csv", rapidcsv::LabelParams(), sp);
for (int i = 0; i < doc_customer.GetRowCount(); i++)
{
auto name =  doc_customer.GetCell<std::string>("name", i);
auto address = doc_customer.GetCell<std::string>("address", i);
std::cout << "customer: " << name << ", " << address << std::endl;
}
}
int main()
{
read_customer();  
return 0;
}

相关内容

  • 没有找到相关文章

最新更新