fork(1) download
  1. #include <iostream>
  2.  
  3. class Store {
  4. enum { MaxCount = 64 };
  5. float store_[MaxCount] {};
  6. size_t count_ = 0;
  7. public:
  8. // return the maximum number of elements we can store
  9. size_t capacity() const { return MaxCount; }
  10. // true/false: is the store empty?
  11. bool empty() const { return count_ == 0; }
  12. // return the current count
  13. size_t size() const { return count_; }
  14.  
  15. bool add(float value) {
  16. if (count_ >= capacity()) {
  17. std::cerr << "store is full!\n";
  18. return false;
  19. }
  20. store_[count_] = value;
  21. ++count_;
  22. }
  23. // reset
  24. void clear() {
  25. count_ = 0; // we don't actually need to change the store
  26. }
  27. // allow array-like usage
  28. const float& operator[](size_t index) const { return store_[index]; }
  29. float& operator[](size_t index) { return store_[index]; }
  30. // provide bounds-checked array-ish access
  31. float at(size_t index) const {
  32. if (index >= count_)
  33. throw std::invalid_argument("array index out of bounds");
  34. return store_[index];
  35. }
  36. };
  37.  
  38. int main() {
  39. Store store;
  40. for (size_t i = 0; i < store.capacity(); ++i) {
  41. std::cout << "Enter number #" << i << " or -ve to stop: " << std::flush;
  42. float f = -1;
  43. std::cin >> f;
  44. std::cout << "\n" << f << "\n";
  45. if (f < 0)
  46. break;
  47. store.add(f);
  48. }
  49. std::cout << "You entered " << store.size() << " values:";
  50. for (size_t i = 0; i < store.size(); ++i) {
  51. std::cout << ' ' << store[i];
  52. }
  53. std::cout << '\n';
  54. }
  55.  
Success #stdin #stdout 0s 3472KB
stdin
10
42
1
3
5.2
-1
stdout
Enter number #0 or -ve to stop: 
10
Enter number #1 or -ve to stop: 
42
Enter number #2 or -ve to stop: 
1
Enter number #3 or -ve to stop: 
3
Enter number #4 or -ve to stop: 
5.2
Enter number #5 or -ve to stop: 
-1
You entered 5 values: 10 42 1 3 5.2