How do you append a number to an LPCTSTR? A library I am using takes an LPCTSTR for a com port address. I know how to do this with char* , but not with a LPCTSTR. This is what I want to do (assuming sprintf as is worked with these, which I know it doesn’t)
LPCTSTR PortString;
int ComPortNumber;
sprintf(PortString,"COM%d",ComPortNumber);
Such that when that is done, the LPCTSTR PortString, would contain “COM9” if 9 was stored in the ComPortNumber integer.
An LPCTSTR is a pointer to a TCHAR – in other words a pointer to a string. In the code snippet you provide, it points to some random area of memory and running the code is undefined behavior since you are accessing some random area of memory by dereferencing an uninitialized pointer.
Try this code instead:
I used the
Tvariants of the calls and types to ensure that you code would compile in both ANSI/MBCS and UNICODE modes, and the new “secure” variant of_sntprintfto help reduce the chance of buffer overrruns.In real production code you should check the return address from the
_sntprintf_scall for errors.One last point: be careful to not return
PortStringto whoever calls this function, as it is stack based, and when this function exits, the buffer will disappear. If you do this your program will crash while you’re debugging/testing if you’re lucky. If you’re not lucky, it may appear to work correctly but it will be a ticking timebomb.