tags:

views:

105

answers:

4

How do I append a string to a char? strcat(TotalRam,str); is what i got but it does not support strings

+2  A: 

std::String has a function called c_str(), that gives you a constant pointer to the internal c string, you can use that with c functions. (but make a copy first)

Chris H
+2  A: 

Use + on strings:

std::string newstring = std::string(TotalRam) + str;

If you want it as a char[] instead, you need to allocated memory on the heap or stack first. After that, strcat or sprintf are possible options.

Dirk Eddelbuettel
A: 

for performance, do this:

char ministring[2] = {0,0};
// use ministring[0] as your char, fill it in however you like
strcat(ministring,str);

The char array is stack-allocated so it is extremely fast, and the second char with the value of zero acts as a string terminator so that functions like strcat will treat it as a 'c' string.

David Gladfelter
Almost exactly what I put +1 for trying
H4cKL0rD
I think you've got your parameters backwards on the strcat. If you meant it to be the way you have it written, then this will result in stack corruption because str will be appended to your stack allocated ministring. if str is long enough, this will corrupt other values below ministring on the stack. (Including the return address pointer, resulting in a buffer overflow attach that could easily be used for remote code execution.)
SoapBox
My bad, I haven't used c string functions in quite some time.
David Gladfelter
+1  A: 

You can't append a string to a char, you can only append a string to a string (or a char* if using the C string functions). In your example, you'll have to copy (the char) TotalRam into a string of some sort, either a C++ std::string, or make a char[2] to hold it and the required terminating NULL character. Then you can either use the C++ string with C++ functions or the char[2] with strcat and friends.

Mike Kale