Sign in to follow this  

Using strings and char array in classes

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

This topic is 2547 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this