Jump to content
  • Advertisement
Sign in to follow this  
Demx

Using strings and char array in classes

This topic is 2764 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

Hi

i'd like to know how to send a message ( string or char ) to a object funtion setmessage() and recieve it from getmessage()

for example:

class Name{

char nam[20];

public:

void setname(char input[20])
{
nam[20]=input[20];
}

char getname()
{
return nam[20];
}

};

main(){

char name[20];

scanf("%c",&name);

Name n;

n.setname(name);

printf("%c",n.getname() );


}

Or somthing like that.. please explain :)

Share this post


Link to post
Share on other sites
Advertisement
I'd recommend you use the STL std::string. Most of your problems will be taken care of.

First, if you fix the size of the character buffer ( char nam[20] ), you will eventually run into problems with buffer overrun unless you carefully check the length of the strings. Again, using std::string will take care of that problem for you.

Be careful in your code to intialize your character buffer with an end NULL:

class Name
{
Name():nam[0]=0 {}
char nam[20];
//...
};

In its simplest form, with very little error checking:

void setname(char *input, size_t length)
{
if( length > 19 ) return; // too long
strcpy_s(nam,length,input);
}
char *getname()
{
return nam;
}

Again, use std::string and avoid the problems. If you must use char[] instead of std::string, use the string-safe versions ( strcpy_s vs. strcpy, etc. ) of the string manipulation functions.

Share this post


Link to post
Share on other sites

class Name
{
Name():nam[0]=0 {}
char nam[20];
//...
};


This code is not legal. I don't believe you can initialise arrays like that (without wrapping them in a structure, and that merely moves the problem). You can do the work in the constructor body.

But yes, use std::string unless you have a compelling reason not to.

Share this post


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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!