0

How to name objects during runtime

Hello! I have a little problem. I am doing a program and I need to create object, whose name is chosen by user. I am doing it in Java, but I have the same problem in C++. String name; cin>>name; Player name; The third line doesn't work. It creates object of type player named "name", but I need it to have name written in the name string variable. Can you help me please?

12th Apr 2018, 9:15 AM
Jan Štěch
Jan Štěch - avatar
8 Respuestas
+ 2
Oh ok. Just use an object vector for this. I think I have a code for showcase.... Here it is: https://code.sololearn.com/cU2KHvrLZQvl/?ref=app
12th Apr 2018, 10:18 AM
Alex
Alex - avatar
+ 5
In your code you attemp to create two different variables with the same name in the same scope. It is error in any language. For holding additional data in object use additional field in class (struct) that represents object's type. Eg: struct Player { string name; // ... other data // declaring constructor for use Player (string n) : name(n) {} }; int main() { string name; cin >> name; Player p(name); } now object 'p' contains inputed name
12th Apr 2018, 9:27 AM
Rull Deef 🐺
Rull Deef 🐺 - avatar
+ 1
Or use a map for this. Here is an example: https://code.sololearn.com/c47udIRQsNo2/?ref=app The reason this doesn't work like you want to use it is that the string is changed in runtime and the name of the object at compiletime. With a map you can access your object with using the name you gave it as key. It's more complicated then just naming the object yourself so think twice if it is worth it.
12th Apr 2018, 9:52 AM
Alex
Alex - avatar
+ 1
You can also use the mapping method and fill it in a similar setup as in the object vector code
12th Apr 2018, 10:19 AM
Alex
Alex - avatar
+ 1
ok, thank you very much. You helped me a lot.
12th Apr 2018, 10:27 AM
Jan Štěch
Jan Štěch - avatar
0
Any reason why you want to do that?
12th Apr 2018, 9:23 AM
Alex
Alex - avatar
0
Thank you for your answers, but consider following situation: I don't know how many players will a user register. I need to name objects p1, p2, p3 ... pn. How can I create for example 10 objects using a cycle and not have to write Player p1; Player p2; Player p3; ... Player p10;
12th Apr 2018, 10:15 AM
Jan Štěch
Jan Štěch - avatar
0
your welcome
12th Apr 2018, 10:34 AM
Alex
Alex - avatar