samedi 10 août 2019

How do I add a string to a vector (and subsequently display it)?

I am 4 hours-new to C++ and have hit a brick wall with string vectors. When trying to add multiple strings to a string vector, I keep erroring out. I'd like to use push_back.

I would also like to display this string vector, but I'm not sure how (I know how to display non-vectors). Given that I have not been able to add a string to a vector of strings, I did not attempt to display the vector of strings yet.

profile.hpp

#include <iostream>
#include <vector>

class Profile 
{
private:
    std::string name;
    std::string city;
    std::string country;
    int age;
    std::vector<std::string> hobbies;

public:
    std::vector<std::string> add_hobbies(std::string new_hobbies);
};

profile.cpp

#include <iostream>
#include "profile.hpp"

Profile::Profile(std::string new_name, int new_age, std::string new_city, std::string new_country)
    : name(new_name), age(new_age), city(new_city), country(new_country) 
{}

void Profile::add_hobbies(std::string new_hobbies) 
{
    hobbies.push_back(new_hobbies);
}

app.cpp

#include <iostream>
#include "profile.hpp"
int main()
{
    Profile sam("Sam Drakkila", 30, "New York", "USA");
    sam.add_hobbies("Play golf", "Read books", "Eat tennis balls"); // This doesn't seem to work. 
}

g++ app.cpp profile.cpp. Prints a massive log of errors.

Aucun commentaire:

Enregistrer un commentaire