我一直在嘗試閱讀以下數據表併爲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'讀取每個數據,方法是將逗號指定爲行分隔符。但這實在太開放了:有很多方法可以做到這一點,所以投票結果太寬泛。 –