Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am reading file that contains

Johh, 13, soccer, cricket
Mitchell, 14, cricket
Michael, 13, football, cricket, soccer
(all three in separate lines starting from names)

I have created class with objects called name, age and favourite sport. is it possible in C++ to combine stuff after age (which are favourite sports) into one object rather then having to write favourite sport1, favourite sport2 etc. Example for John it can be student.getname() = john, student.getAge() = 13 and student.getFavSport = soccer,cricket. etc

really stuck at this part, have never been taught, any help would be appreciated Thank you

What I have tried:

I have so far created class and objects
Updated 9-Apr-21 1:06am

Yes, just add a collection of Sport objects to the Student class (or whatever the people are) and add each sport as a separate instance to that.

Exactly what collection depend on the environment you are running in, a CLI project might use a .NET List for example, or there are loads of other types: Containers - C++ Reference[^]
Share this answer
Yes, you can.
Try, for instance
#include <vector>
#include <iostream>
using namespace std;
class student
  string name;
  int age;
  vector <string> sport;

  student(string name, int age, vector<string> sport):name(name), age(age), sport(sport){}

  string get_name() const { return name; }
  int get_age() const { return age;} const

  vector<string> & get_sport() const { return sport;}


int main()
  vector<student> v = {
    { "Johh", 13, { "soccer", "cricket" }},
    { "Mitchell", 14, { "cricket" }},
    { "Michael", 13, {"football", "cricket", "soccer"}},

  for (const auto & s : v)
    cout << s.get_name() << ", " << s.get_age();
    for ( const auto & sport : s.get_sport() )
      cout << ", " << sport;
    cout << endl;
Share this answer
Member 14559341 9-Apr-21 7:22am    
@CPallini Thank you very much, this is very helpful. I noticed you separated the sport in vector v from age and name using separate{}. Possible to know how to do similar whilst reading from file? thank you
CPallini 9-Apr-21 8:50am    
Retrieving the items from a file, as far as I know, requires a different approach (you have to iterate, in order to fill the vector of strings. In my code, a similar iteration is used for the output).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900