Reputation: 480
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.
Upvotes: 3
Views: 7349
Reputation: 480
Thanks to WhozCraig, I got the answer:
LPCSTR str1 = "foo",
str2 = "bar";
std::string(str1).append(str2).c_str();
std::cout<<str1;
Returns
foobar
Upvotes: 2
Reputation: 141658
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.
Upvotes: 0
Reputation: 831
Since LPCSTR
is a CONST CHAR*
i used this,
(string(dir) + string(originalFileName)).c_str()
Upvotes: 5
Reputation: 1851
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.
Upvotes: 2