读取C++中的csv列名
Read csv column names in C++
我是面向对象编程的新手。首先,我试图从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
相关文章:
- 正在将csv文件读取为双精度矢量
- 如何选择在 csv 文件中输出的位置
- 有没有办法在不使用 getline() 的情况下从.csv文件中读取?
- 如何从 CSV 获取数据并将其存储在 C++ 中的表对象中
- 无法读取C++中的 CSV 文件
- 流:CSV 文件中的换行符
- 是否可以使用 Python csv 阅读器读取使用 C++ std::setw 生成的文件?
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 将一维数组写入 CSV C++中的不同列?
- 如何从CSV加载堆栈?C++
- 如何正确格式化csv文件?
- 正在分析CSV文件-C++
- 如何获取组件和搜索 CSV 文件
- C++ 中的 CSV 文件管理(特别是设置标头和每个标头将分别具有的值)
- 无法逐行读取.csv文件
- 以CSV格式编写特征矢量Xd
- 非常快速地阅读 CSV 文件
- 读取和存储 CSV 数据
- 读取C++中的csv列名
- 如何将列名设置为csv文件-c++