"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.
strncpy(buffer, a, sizeof(buffer));
strncat(buffer, b, sizeof(buffer));
// now buffer has the two strings joined together.
Your attempt to use std::string failed for a similar reason. You said:
std::string a = "Start";
std::string b = a + " End";
This translates to
b = (std::string)a + (const char*)" End";
Which should be ok except that it creates an extra string, what you probably wanted is
std::string a = "Start";
a += " End";
If you are getting compile errors doing this, please post them (Make sure you #include ).
Or you could do something like:
std::string addTwoStrings(const std::string& a, const std::string& b)
{
return a + b; // works because they are both strings.
}
All of the following work: (see live demo http://ideone.com/Ytohgs)
#include <iostream>
#include <string>
std::string addTwoStrings(const std::string& a, const std::string& b)
{
return a + b; // works because they are both strings.
}
void foo(const char* a, const char* b)
{
std::string str = a;
std::cout << "1st str = [" << str << "]" << std::endl;
str += " ";
std::cout << "2nd str = [" << str << "]" << std::endl;
str += b;
std::cout << "3rd str = [" << str << "]" << std::endl;
str = addTwoStrings(a, " ");
std::cout << "4th str = [" << str << "]" << std::endl;
str = addTwoStrings(str, b);
std::cout << "5th str = [" << str << "]" << std::endl;
}
int main()
{
foo("hello", "world");
}
*1 Or more accurately, "cannot be changed in-situ" - you can use it in expressions, etc, so for example, e.g.
const size_t len = strlen("hello");
size_t newLen = len + strlen("world");
// but this would not be legal:
len += 2; // error: len is const.
2 "const char a + const char* b" is actually trying to add two pointers not two strings, the result would be the address of string a plus the address of string b, the sum of which would be some random memory location