How concatenate a string and a const char?
Asked Answered
P

2

24

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

string a = "hello ";
const char *b = "world";

const char *C;
Phonotypy answered 20/4, 2012 at 13:28 Comment(0)
C
45
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.

Chickaree answered 20/4, 2012 at 13:29 Comment(3)
Better way would be to const char *C = (a + b).c_str();. It doesn't modify string a.Plough
(a + b).c_str() will leave C pointing at invalid memory, as + creates a temporary string that will go out of scope and be destructed when the statement is finished. This is fine when passing (a + b).c_str() to a function parameter, but not when assigning it to a variable.Enthalpy
@RemyLebeau, thanks, good catch - I just mindlessly incorporated that comment into the answer.Chickaree
H
10

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';
Hernandes answered 20/4, 2012 at 13:32 Comment(2)
You failed to see "...put [...] in C" part of question.Chickaree
@Chickaree I have added a bit moreHernandes

© 2022 - 2024 — McMap. All rights reserved.