Sign in to follow this  

Defining a string in an object

This topic is 4675 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay so i'm working on a text based game (seems to be a hot topic), I'm running into a problem. I have a class set up for room objects, and I've got a string to store a short description of the room. Then I try to define the object's properties and the compiler gives me some error about changing from one varibale size to another. Here's the code; class room{ public: /*Yeah I should have these as private, but I don't have any methods defined in this class yet*/ int roomNo; char roomDesc[256]; }; okay there's the class, everything compiles fine till I try to set the string as somthing. The way I'm doing this is: room world[SIZEX][SIZEY][SIZEZ]; world[1][1][1].roomDesc = "THE CENTER OF THE WORLD"; When that's where the error happens, what am I doing wrong? Thanks for any help -Brandon

Share this post


Link to post
Share on other sites
That's not how strings work in C++. You're basically trying to assign a character pointer to an array. Doesn't work. STL has a string class that'll make things work the way you expect:


#include <string>
using std::string;

class room{
public:
/*Yeah I should have these as private, but I don't have any methods defined in this class yet*/
int roomNo;
string roomDesc;
};

// ...

world[1][1][1].roomDesc = "THE CENTER OF THE WORLD";


Share this post


Link to post
Share on other sites
A char array is not actually a "string" so you can't use = to set it's value. Either use C++ std::string and declare it as string description or else include the old cstring library and set the value with strcpy(world[1][1][1].roomDesc,"THE CENTER OF THE WORLD");

Share this post


Link to post
Share on other sites
Try using an actual string instead of a char array. C-style char arrays can't be used the way you are trying. You can't assign a string to a char array.

#include <string>

using std::string

class room {
public:
int roomNo;
string roomDesc;
};




EDIT: Dang, I'm slow.

Share this post


Link to post
Share on other sites
If you want to use char arrays though, you can always do:

std::strcpy(world[1][1][1].roomDesc, "THE CENTER OF THE WORLD");

found in string library (#include <string>)


check this link for strcpy function and many more:
http://www.cplusplus.com/ref/cstring/index.html

Share this post


Link to post
Share on other sites
Thanks everybody! Everything runs great now! Now I'm gonig to work on rewritting the whole thing so I can manage having health and some enemies running around!

-Brandon

Share this post


Link to post
Share on other sites
Sign in to follow this