我一直在尝试阅读以下数据表并为HUB(行)和另一个对象(大陆)(列)创建对象。由于我不是C++经验丰富的用户,我一直面临一些困难。数据如下。 HUB和破折号后面的数字显示了枢纽的顺序。每个大陆下的其他数字是HUB与大陆之间的相应成本和关税。我希望能来清点例如下面,让这将是73 cout << hub(1)->cont(USA)->transport() << endl;
从逗号分隔的数据文件中读取列C++
,USA,EUROPE,ASIA
HUB1-12000,,,
Transportation Cost,73,129,141
Tariffs,5,5,1
ShippingType,a,b,c
OtherFees,0.6,0.3,0.8
HUB2-11000,,,
Transportation Cost,57,101,57
Tariffs,7,7,5
ShippingType,b,b,d
OtherFees,0.7,0.3,0.6
真的很感谢你的帮助的结果。以下是我迄今为止尝试:
void Hub()
{
string file = "/hubs.csv";
// 1-First read the first line and save the continent name
string str, field;
getline(fin, str);
vector<string> contList;
stringstream linestr(str);
while ( linestr.good())
{
getline(linestr, field, ',');
string contname;
contList.push_back(contname);
}
// 2-Then read the rest
getline(fin, str);
while (!fin.eof()) // Read the whole file
{
stringstream linestr(str);
string contname, order;
if (qstr[0] == 'HUB1' || qstr[0] == 'HUB2')
{
// Read the name of the hub
getline(linestr, hubname, ','); // Read the hub name
getline(linestr, order, ','); // Read the order quantityity
int quantity;
istringstream orderstream(order);
orderstream >> quantity;
// Find the hub and add the order to the hub
Hub* hub = glob->FindHubName(hubname); // this returns a pointer
if (glob->FindHubName(hubname) == nullptr)
{
hubNotFound.push_back(hubname);
getline(fin, qstr);
continue;
}
hub->TotalOrder(quantity);
}
else if (qstr[0] != 'HUB1' || qstr[0] != 'HUB2')
{
// Read costs and tariffs
cout << hub(1)->cont(ASIA)->transport()
}
getline(fin, qstr);
}
fin.close();
}
可以通过'getline'从''头读取每一行。然后,您可以将每行字符串放入一个“istringstream”中,并通过'getline'读取每个数据,方法是将逗号指定为行分隔符。但这实在太开放了:有很多方法可以做到这一点,所以投票结果太宽泛。 –