Inserting a char into a string.

C

Connell Gauld

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
 
I

Ivan Vecerina

Connell Gauld said:
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
 
W

wittempj

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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top