user defined objects

I want to know if its possible to make objects in a loop depending on user input. For example say I want to ask the user if he wants to add another fruit and the user says yes can I code it in a way where it makes an object and assigns values to the object? and it will prompt the user again if he wants to add more fruit? Also I want to be able to go back and pull each individual object and possibly change its values.....is this possible? I'v been trying with vectors but I dont know how to call a specific object to view/edit.

I think you should post the code you have been working on and show us where you are getting stuck.
To be honest..I got stuck here...I realized p is just the pointer and I dont know how to recall a specific object...does that make sense?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include<iostream>
#include<string>
#include<vector>
#include<fstream>
using namespace std;

class fruit{
public:
	string s;


};

int main(){
	string a;
	vector<fruit*> myfruits;
	fruit* p = new fruit();



	int g;
	cin >> g;
}
> I'v been trying with vectors but I dont know how to call a specific object to view/edit.

See: https://www.mochima.com/tutorials/vectors.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <vector>

struct fruit
{
    std::string name ;
};

int main()
{
    std::vector<fruit> fruit_list ; // strongly favour value semantics over pointer semantics

    std::string fruit_name ;
    while( std::cout << "name of fruit (enter an empty string when done)? " &&
           std::getline( std::cin, fruit_name) && !fruit_name.empty() )
    {
        // {fruit_name}: http://www.stroustrup.com/C++11FAQ.html#uniform-init
        fruit_list.push_back( {fruit_name} ) ;
    }

    // for each fruit in fruit_list http://www.stroustrup.com/C++11FAQ.html#for
    for( const fruit& f : fruit_list ) std::cout << f.name << '\n' ;
}
and with out vectors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

class fruit {
public:
    // constuctor //
    fruit(const std::string &name) : name(name) { }
    // getter and setters //
    const std::string &getName() const {
        return name;
    }
    void setName(const std::string &name) {
        fruit::name = name;
    }
    // data //
private:
    std::string name;=
};

using namespace std;
int main() {
    // set name //
    fruit item1("banna");
    // print name //
    cout << item1.getName() << endl;
    // change name //
    item1.setName("peach");
    // print name
    cout << item1.getName() << endl;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.