问题是我必须读取一个包含以下内容的文件:
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
我必须使用矢量对来读取文件,并乘以计数和价格,输出应该是:
oil
66
butter
27.2
bread
21.8
任何想法都将不胜感激!
如果您只想使用std::pair
和std::vector
,那么您可以使用以下程序作为起点(参考(:
版本1:产品名称将重复
#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;
}
您可以/应该使用class
或struct
,而不是使用std::pair
。
上面程序的输出可以在这里看到。输入文件也附在上面的链接中。上述版本1的输出为:
bread: 12
butter: 21
bread: 6.5
oil: 66
butter: 6.2
bread: 3.3
正如您在版本1的输出中看到的,产品的名称是重复的。如果您不希望重复的名称,并且希望将与重复键相对应的值相加,请查看下面给出的版本2:
版本2:产品名称不重复
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int findKey(const std::vector<std::pair<std::string, double>> &vec, const std::string &key)
{ int index = 0;
for(const std::pair<std::string, double> &myPair: vec)
{
if(myPair.first == key)
{
return index;
}
++index;
}
return -1;//this return value means the key was not already in the vector
}
int main()
{
std::ifstream inputFile("input.txt");
std::string line;
std::vector<std::pair<std::string, double>> vec;
std::string name;
double price, count;
if(inputFile)
{ std::getline(inputFile, line, 'n');
while(std::getline(inputFile, line, 'n'))
{
std::istringstream ss(line);
ss >> name;
ss >> count;
ss >> price;
int index = findKey(vec, name);
if(index == -1)
{
vec.push_back(std::make_pair(name, count * price));
}
else
{
vec.at(index).second += (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;
}
版本2的输出是
bread: 21.8
butter: 27.2
oil: 66
这可以在这里看到。