The problem is that i have to read a file that includes:
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
I have to use Vector Pair to read the file and to multiply the count and price and the output should be :
oil
66
butter
27.2
bread
21.8
Any idea would be highly appreciated!
CodePudding user response:
If you only want to use std::pair
and std::vector
then you could use the following program as a starting point(reference):
#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;
}
You can/should instead use a class
or struct
instead of using a std::pair
.
The output of the above program can be seen here. The input file is also attached in the above link.