读取C++中的csv列名

Read csv column names in C++

本文关键字:列名 csv 中的 C++ 读取      更新时间:2023-10-16

我是面向对象编程的新手。首先,我试图从csv文件中读取以下数据结构,解析第一行(标题),并将字符串推回到向量中。其次,我想读取第一行(美国)的客户信息,并提取名称和整数值(14400000)。到目前为止,我现有的代码确实读取了这些列。然而,在一些字符串中有额外的空间并对其进行修剪。

+------------------------------------------------------+
|,ABB LLC,Phil manu ,Products North America Inc.,Mapn, |
+------------------------------------------------------+
| USA-14400000,,,,                                     |
| Quantity,14155572,14435598,14298563,14311206         |
| Index,US-GC,EU-HT,AS-IR,US-PT                        |
| Period(WEEKS),3,3,3,3                                |
| cost,6278,5341,7394,7069                             |
+------------------------------------------------------+

这是我的密码。

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
void ReadTest()
{
  string filename = doe->ScenarioDir( ) + "/test.csv"; // Read data
  ifstream fin( filename );
  if ( fin == NULL )
  {
    cout << "Missing test.csv file." << endl; 
    exit(1);
  }
  cout << "nReading file " << filename << endl;
  vector<string> suppliersList;
  string str, supplierName;
  getline( fin, str );
  stringstream linestr( str );
  getline( linestr, supplierName,',' );
  while (  linestr.good() )
  {
    getline( linestr, supplierName, ',' );
    suppliersList.push_back(supplierName);
  }
    std::cout << suppliersList[0] << ' ';
}

输出为:ABB LLC

如有任何帮助,我们将不胜感激!

您的代码按设计工作。下面的行显然只打印第一个元素:

std::cout << suppliersList[0] << ' ';

如果您将其更改如下:

for (auto &x: suppliersList)
     std::cout << x << ' ';

您将获得完整的列表:

ABB LLC Phil manu  Products North America Inc. Mapn  

顺便说一下:

  • 你真的应该用if(!fin)代替if(fin==NULL)
  • 并且您应该在读取操作上循环:while(getline( linestr, supplierName, ',' ))而不是while(linestr.good()),然后是一个即使失败也会尝试处理的读取

编辑:如何清除空格

如果您想去掉空格,请使用copy_if()back_inserter()来执行以下操作:

...
string str, field;
...
getline( linestr, field,',' );
while ( getline( linestr, field, ',' ) )
{
    string supplierName;
    copy_if(field.begin(), field.end(), back_inserter<string>(supplierName),[](char a){return !isspace(a);});
    suppliersList.push_back(supplierName);
}
...

这将给你:

ABBLLC Philmanu ProductsNorthAmericaInc. Mapn