By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,305 Members | 1,619 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

Inserting a char into a string.

P: n/a
Hey,
Sorry if this is a really stupid question - I'm new to C++.

I have a program like this:

std::string str;
....
....
....
char buffer[4];

The variable buffer has been filled with four characters.
How do I now make str equal to buffer?
ie I have "ABCD" in buffer and I would like "ABCD" in str.

Thanks
Connell
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"Connell Gauld" <co*****@freebreakfast.co.uk> wrote in message
news:cu**********@news8.svr.pol.co.uk...
Hey,
Sorry if this is a really stupid question - I'm new to C++.

I have a program like this:

std::string str;
...
...
...
char buffer[4];

The variable buffer has been filled with four characters.
How do I now make str equal to buffer?
ie I have "ABCD" in buffer and I would like "ABCD" in str.


str.assign( buffer, buffer+4 );
or
str.assign( buffer, 4 );

(or pass the same two parameters defining a range to
the constructor of std::string).

hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 23 '05 #2

P: n/a
assigning works as well:
string s;
char c[5];
memset(&c, '\0', sizeof(c));
strncpy(c, "ABCD", 4);

s = c;

cout << c << endl;
cout << s << endl;

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.