stock01.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // stock01.cpp -- revised show() method
  2. #include <iostream>
  3. #include "stock00.h"
  4. void Stock::acquire(const std::string & co, long n, double pr)
  5. {
  6. company = co;
  7. if (n < 0)
  8. {
  9. std::cerr << "Number of shares can't be negative; "
  10. << company << " shares set to 0.\n";
  11. shares = 0;
  12. }
  13. else
  14. shares = n;
  15. share_val = pr;
  16. set_tot();
  17. }
  18. void Stock::buy(long num, double price)
  19. {
  20. if (num < 0)
  21. {
  22. std::cerr << "Number of shares purchased can't be negative. "
  23. << "Transaction is aborted.\n";
  24. }
  25. else
  26. {
  27. shares += num;
  28. share_val = price;
  29. set_tot();
  30. }
  31. }
  32. void Stock::sell(long num, double price)
  33. {
  34. using std::cerr;
  35. if (num < 0)
  36. {
  37. cerr << "Number of shares sold can't be negative. "
  38. << "Transaction is aborted.\n";
  39. }
  40. else if (num > shares)
  41. {
  42. cerr << "You can't sell more than you have! "
  43. << "Transaction is aborted.\n";
  44. }
  45. else
  46. {
  47. shares -= num;
  48. share_val = price;
  49. set_tot();
  50. }
  51. }
  52. void Stock::update(double price)
  53. {
  54. share_val = price;
  55. set_tot();
  56. }
  57. void Stock::show()
  58. {
  59. using std::cout;
  60. using std::ios_base;
  61. // set format to #.###
  62. ios_base::fmtflags orig = cout.setf(ios_base::fixed);
  63. int prec = cout.precision(3);
  64. cout << "Company: " << company
  65. << " Shares: " << shares << '\n';
  66. cout << " Share Price: $" << share_val;
  67. // set format to *.**
  68. cout.precision(2);
  69. cout << " Total Worth: $" << total_val << '\n';
  70. // restore original format
  71. cout.setf(orig, ios_base::floatfield);
  72. cout.precision(prec);
  73. }