How to Concatenate Two LPCSTRs

6.7k Views Asked by At

I have two LPCSTRs I need to concatenate like so:

if (!rename(directory + originalFileName, directory + fileName)){
    std::cout<<originalFileName<<std::endl<<fileName<<std::endl<<std::endl;
}

The only problem however is that I can't use the + operator here. How can I safely concatenate two LPCSTRs like this?

EDIT: Note that an LPCSTR is defined as a const * char while an LPCTSTR is defined as const TCHAR*. The two are different when UNICODE and/or _UNICODE are defined. In this case, they are.

4

There are 4 best solutions below

2
On BEST ANSWER

Thanks to WhozCraig, I got the answer:

LPCSTR str1 = "foo",
       str2 = "bar";

std::string(str1).append(str2).c_str();
std::cout<<str1;

Returns

foobar
1
On

Since these strings are const you will need a new buffer to hold the results. That means finding the length of the strings with 'strlen', allocating a buffer with 'new', and copying the strings with 'strcpy' and 'strcat'

That's a hint for how to learn it, instead of me writing the code for you.

Also, there are other options such as using std::string or CString depending on your toolset.

1
On

Since LPCSTR is a CONST CHAR* i used this,

(string(dir) + string(originalFileName)).c_str()
0
On

You may use the std::string class to do the heavy lifting because it contains overloaded operator+. However you must ensure that the std::string object is not destroyed before you attempt to read its contents.

One way (in C++03) would be:

std::string dest = std::string(directory) + originalFileName;
std::string src = std::string(directory) + fileName;

if (!rename(dest.c_str(), src.c_str())
    // whatever...

Consider storing directory as a std::string in the first place.