Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How concatenate a string and a const char?

Tags:

I need to put "hello world" in c. How can I do this ?

string a = "hello "; const char *b = "world";  const char *C; 
like image 496
xRobot Avatar asked Apr 20 '12 13:04

xRobot


People also ask

How do I add a const char to a string?

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).

Can we concatenate string and character?

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.

Can I concatenate string with char C++?

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.

How do you add two const characters?

"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.


1 Answers

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 strings (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.

like image 101
Griwes Avatar answered Sep 18 '22 14:09

Griwes