I need to put "hello world" in c. How can I do this ?
string a = "hello "; const char *b = "world"; const char *C;
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. Better way would be to const char *C = (a + b).
Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output.
C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.
"const" means "cannot be changed(*1)". So you cannot simply "add" one const char string to another (*2). What you can do is copy them into a non-const character buffer. const char* a = ...; const char* b = ...; char buffer[256]; // <- danger, only storage for 256 characters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With