This is for a simple game and I am trying to learn how to apply C++ in an existing project (that's how I learn best), I have experience programming in C# and other high level languages so it is quite new to me still. So I have this list of races:
const char* Races[] = {
"Demon",
"Human",
"Elf",
"Orc",
"Aliens"
};
At one point I receive the registration of a user and a race is selected. I save away all the information of the user to a struct and I want to save the full name of the race to this struct as well.
struct User_t {
unsigned int RaceID;
char Race[16];
};
The following code is what I got to put the values inside the struct:
User_t User;
User.RaceID = 3;
strcpy(User.Race, Races[User.RaceID]);
This, however, does not work. This is part of a game and the exception handling is horrible (it basically crashes the game without any error visible). I am trying to figure out what I am doing wrong. Any suggestions, perhaps suggestions on other things as well?
I am trying to figure out what I am doing wrong. Any suggestions, perhaps suggestions on other things as well?
You are trying to use C++ as if it was C (which is possible syntactically), and you do not know C nor C++ well enough to do that.
Do yourself a favor and do it in real C++:
std::string Races[] = {
"Demon",
"Human",
"Elf",
"Orc",
"Aliens"
};
struct User {
unsigned int RaceID;
std::string Race;
explicit User(unsigned int rid)
: RaceID(rid)
, Race(Races[rid])
{}
};
User user(3);
std::cout << user.Race << '\n';
I would suggest that you look in to enum class{}
. It's easier to make your code less error-prone.
You could write your code like this:
enum class eRaces
{
eDemon,
eHuman,
eElf,
eOrc,
eAlien,
};
struct User
{
eRaces myRace;
};
User User;
User.myRace = eRaces::eElf;
Assuming that scope of Races
array is global you can simply avoid copying it and just do something like this:
struct User_t {
unsigned int RaceID;
const char* Race;
};
User_t User;
User.RaceID = 3;
User.Race = Races[User.RaceID];
You can also use std::string
as mentioned in comments but you wont avoid copying it. Since you develop game i think that performance has higher priority over objectivity of c++ language.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.