I do not understand why my output is coming out as wrong. I have attached my code and my result(highlighted the issue)
I am adding a coin to the insertCoin function in VendingMachine class. As soon as I add 10 cents to this function, it prints out error-> Does not accept 10 cents. I am converting the input to float using static_cast. I spent some good time on this and at this point, I feel I just cannot see the issue probably because I dont understand some concept.
Also as a quick background, new to c++ and trying to get my object oriented programming up to date. Trying to make a Vending machine product hehe. Thank you again !
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <utility>
#include <stdlib.h>
using namespace std;
class Item
{
private:
string m_name;
float m_cost;
public:
Item(string t_name,float t_cost):m_name(t_name),m_cost(t_cost)
{
}
string getName()
{
return m_name;
}
float getCost()
{
return m_cost;
}
};
class VendingMachine
{
private:
vector<Item> m_totalItems;
unordered_map<string,Item>m_products;
float m_remainingCharges{0};
float m_moneyInserted{0};
size_t itemCount{0};
public:
VendingMachine()
{
}
void addItemToVendingMachine(string t_name,size_t t_cost)
{
float temp=static_cast<float>(t_cost)/static_cast<float>(100);
Item item(t_name,temp);
m_totalItems.push_back(item);
m_products.insert(make_pair(t_name,item));
}
bool chooseProduct(string t_name)
{
for(auto item:m_totalItems)
{
if(item.getName()==t_name)
{
m_remainingCharges=item.getCost();
return true;
}
itemCount++;
}
cout<<"Item not currently available: "+t_name<<endl;
return false;
}
void insertCoin(size_t t_coin)
{
float temp=static_cast<float>(t_coin);
if(t_coin<=50)
{
temp/=100;
cout<<temp<<endl;
}
if(temp==0.01 or temp==0.05 or temp==0.1 or temp==1.00 or temp==2.00 or temp==0.25 or temp==0.50)
{
m_moneyInserted+=temp;
m_remainingCharges-=m_moneyInserted;
}
else
{
cout<<"Does not accept: "<< t_coin<<" ,please insert correct coin."<<endl;
return;
}
}
pair<Item,float> getProduct()
{
auto item=m_totalItems[itemCount];
auto itemBack=m_totalItems.back();
m_totalItems[itemCount]=itemBack;
m_totalItems.pop_back();
return make_pair(item,abs(m_remainingCharges));
}
float refund()
{
if(m_remainingCharges<0)
return abs(m_remainingCharges);
else
return 0;
}
void resetOperator()
{
m_remainingCharges=0;
m_moneyInserted=0;
itemCount=0;
}
};
int main()
{
Item item("Candy",0.50);
cout<<item.getName()<<" ";
cout<<item.getCost()<<endl;
VendingMachine machine;
machine.addItemToVendingMachine("CANDY",10);
machine.addItemToVendingMachine("SNACK",50);
machine.addItemToVendingMachine("Coke",25);
machine.insertCoin(10);
machine.insertCoin(25);
machine.insertCoin(50);
machine.chooseProduct("CANDY");
auto temp=machine.getProduct();
cout<<temp.first.getName()<<endl;
cout<<temp.second<<endl;
machine.resetOperator();
return 0;
};