Reputation: 26565
I need to put "hello world" in c. How can I do this ?
string a = "hello ";
const char *b = "world";
const char *C;
Upvotes: 25
Views: 82356
Reputation: 9049
string a = "hello ";
const char *b = "world";
a += b;
const char *C = a.c_str();
or without modifying a
:
string a = "hello ";
const char *b = "world";
string c = a + b;
const char *C = c.c_str();
Little edit, to match amount of information given by 111111.
When you already have string
s (or const char *
s, but I recommend casting the latter to the former), you can just "sum" them up to form longer string. But, if you want to append something more than just string you already have, you can use stringstream
and it's operator<<
, which works exactly as cout
's one, but doesn't print the text to standard output (i.e. console), but to it's internal buffer and you can use it's .str()
method to get std::string
from it.
std::string::c_str()
function returns pointer to const char
buffer (i.e. const char *
) of string contained within it, that is null-terminated. You can then use it as any other const char *
variable.
Upvotes: 45
Reputation: 16168
if you just need to concatenate then use the operator +
and operator +=
functions
#include <string>
///...
std::string str="foo";
std::string str2=str+" bar";
str+="bar";
However if you have a lot of conacatenation to do then you can use a string stream
#include <sstream>
//...
std::string str1="hello";
std::stringstream ss;
ss << str1 << "foo" << ' ' << "bar" << 1234;
std::string str=ss.str();
EDIT: you can then pass the string to a C function taking a const char *
with c_str()
.
my_c_func(str1.c_str());
and If the C func takes a non const char * or require ownership you can do the following
char *cp=std::malloc(str1.size()+1);
std::copy(str1.begin(), str2.end(), cp);
cp[str1.size()]='\0';
Upvotes: 10