3

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 Answers4

5

Since LPCSTR is a CONST CHAR* i used this,

(string(dir) + string(originalFileName)).c_str()
chathux
  • 821
  • 8
  • 17
  • 3
    Note that this can only be used so long as you do not use the result past the end of the *full-expression* containing it – M.M Aug 15 '15 at 03:41
2

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.

Mark Taylor
  • 1,843
  • 14
  • 17
2

Thanks to WhozCraig, I got the answer:

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

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

Returns

foobar
  • Nice job --- I suspect you won't be "a terrible programmer" for very long! – B. Nadolson Aug 15 '15 at 03:29
  • 4
    This answer is wrong as it returns a dangling pointer. When working with raw pointers you must always think about the lifetime of the object the pointer is pointing to. – M.M Aug 15 '15 at 03:39
0

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.

M.M
  • 138,810
  • 21
  • 208
  • 365