fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4.  
  5. int main()
  6. {
  7. enum Currency{ Silver = 10, Gold = 50, Silver10oz = 100, Gold10oz = 500 };
  8. std::map<std::string, unsigned> weapons
  9. {
  10. {"M240", 1250u},
  11. {"M249", 3150u}
  12. };
  13.  
  14. std::cout << "Weapons:" << std::endl;
  15. for(auto const &it: weapons) //std::pair<std::string, unsigned> instead of auto
  16. {
  17. std::cout << it.first << " = $" << it.second << std::endl;
  18. }
  19. std::cout << "Which weapon would you like to purcahse? ";
  20. std::string weaponToPurchase = "";
  21. std::cin >> weaponToPurchase;
  22.  
  23. auto selectedWeapon = weapons.find(weaponToPurchase); //auto can be replaced with
  24. //std::map<std::string, unsigned>::iterator
  25.  
  26. if(selectedWeapon != weapons.end()) //it was found
  27. {
  28. std::cout << "Please enter the number of silver, silver 10 oz, gold, and gold 10 oz"
  29. << " you are going to use for the purchase(separated with spaces): ";
  30. unsigned silver = 0u;
  31. unsigned silver10oz = 0u;
  32. unsigned gold = 0u;
  33. unsigned gold10oz = 0u;
  34. std::cin >> silver >> silver10oz >> gold >> gold10oz;
  35.  
  36. unsigned paid = Silver * silver + silver10oz * Silver10oz +
  37. Gold * gold + Gold10oz * gold10oz;
  38. int owed = selectedWeapon->second - paid;
  39. std::cout << "You gave me $" << paid;
  40. if(owed > 0)
  41. {
  42. std::cout << " and still owe $" << owed << std::endl; //charage them again
  43. }
  44. else if(owed < 0)
  45. {
  46. std::cout << " which is an extra $" << -owed << std::endl;
  47. }
  48.  
  49. }
  50. else
  51. {
  52. std::cout << "That weapon was not found" << std::endl;
  53. }
  54. return 0;
  55. }
Success #stdin #stdout 0s 3436KB
stdin
M240
0 2 1 2
stdout
Weapons:
M240 = $1250
M249 = $3150
Which weapon would you like to purcahse? Please enter the number of silver, silver 10 oz, gold, and gold 10 oz you are going to use for the purchase(separated with spaces): You gave me $1250