問題是我必須讀取一個包含以下內容的檔案:
type count price
bread 10 1.2
butter 6 3.5
bread 5 1.3
oil 20 3.3
butter 2 3.1
bread 3 1.1
我必須使用 Vector Pair 來讀取檔案并乘以計數和價格,輸出應該是:
oil
66
butter
27.2
bread
21.8
任何想法將不勝感激!
uj5u.com熱心網友回復:
如果你只想使用std::pair和std::vector那么你可以使用下面的程式為起點(參考):
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main()
{
std::ifstream inputFile("input.txt"); //open the file
std::string line;
std::vector<std::pair<std::string, double>> vec;
std::string name;
double price, count;
if(inputFile)
{ std::getline(inputFile, line, '\n');//read the first line and discard it
while(std::getline(inputFile, line, '\n'))//read the remaining lines
{
std::istringstream ss(line);
ss >> name; //read the name of the product into variable name
ss >> count;//read the count of the product into variable count
ss >> price;//read the price of the product into variable price
vec.push_back(std::make_pair(name, count * price));
}
}
else
{
std::cout<<"File cannot be opened"<<std::endl;
}
inputFile.close();
//lets print out the details
for(const std::pair<std::string, double> &elem: vec)
{
std::cout<< elem.first<< ": "<< elem.second<<std::endl;
}
return 0;
}
您可以/應該使用 aclass或struct代替使用 a std::pair。
上面程式的輸出可以在這里看到。輸入檔案也附在上面的鏈接中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/351916.html
上一篇:拆分函式Julia中的分隔符
