Challenge: Counting Objects
Completed
Write a class Ticket with a static int sold counter. Each new Ticket gets a number one higher than the last (starting at 1). Read n, then n names. Create a Ticket for each name and print Ticket 1: Ana and so on, then Sold: n using the static counter.
Input
n, then n names.
Output
n ticket lines, then Sold: n.
Example
Input
3 Ana Ben Cara
Output
Ticket 1: Ana Ticket 2: Ben Ticket 3: Cara Sold: 3
Editor
C++
Hints
Declare static int sold; inside the class and int Ticket::sold = 0; outside it.
In the constructor: sold++; then number = sold;
Solution explanation
All tickets share one sold counter, while each ticket keeps its own number.
Show solution
#include <iostream>
#include <string>
using namespace std;
class Ticket {
public:
static int sold;
int number;
string name;
Ticket(string n) : name(n) {
sold++;
number = sold;
}
};
int Ticket::sold = 0;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string name;
cin >> name;
Ticket t(name);
cout << "Ticket " << t.number << ": " << t.name << "\n";
}
cout << "Sold: " << Ticket::sold << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module