Write a class whose methods enforce a rule.
What to build
A class that can never go past its limit.
Requirements
Clicker(int limit)starts at a count of 0.click()adds 1, unless the limit has been reached.reset()sets the count back to 0.count()isconst, and returns the count.- Do not change
main.
Input
The first line has the limit and n. The next line has n commands, each c, r or p.
Output
One line for each p.
Constraints
The limit is from 0 to 1000, and n is from 1 to 1000.
Example
Input:
2 4
c c c p
Output:
2
Why it works
With count private, there is no way to go past the limit, because click is the only code that can add to it.
Examples
Example 1 · Input
2 4 c c c p
Expected output
2
Example 2 · Input
5 4 c r c p
Expected output
1
Hints
Hint 1
Keep count private.
Hint 2
In the constructor, set the limit from the argument and the count to 0.
Hint 3
click only adds when the count is below the limit.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
class Clicker {
int limit_;
int count_;
public:
Clicker(int limit) : limit_(limit), count_(0) {}
void click() {
if (count_ < limit_) count_++;
}
void reset() { count_ = 0; }
int count() const { return count_; }
};
int main() {
int limit, n;
cin >> limit >> n;
Clicker c(limit);
for (int i = 0; i < n; i++) {
char command;
cin >> command;
if (command == 'c') c.click();
else if (command == 'r') c.reset();
else cout << c.count() << endl;
}
return 0;
}