我是面向对象编程的新手。首先,我试图从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
非常感谢任何帮助!
答案 0 :(得分:2)
您的代码按设计运行。以下行显然只打印第一个元素:
std::cout << suppliersList[0] << ' ';
如果你改变它如下:
for (auto &x: suppliersList)
std::cout << x << ' ';
您将获得完整列表:
ABB LLC Phil manu Products North America Inc. Mapn
顺便说一下:
if(fin==NULL)
替换为if(!fin)
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