user7661932
user7661932

Reputation:

How concatenate a TCHAR array with a string?

i have the following code:

enter code here
TCHAR szSystemDirectory[MAX_PATH] ;
GetSystemDirectory(szSystemDirectory, MAX_PATH) ;
_stprintf(szSystemDirectory, _T("%s"), L"\\");

AfxMessageBox(szSystemDirectory);

and wants concatenate two slashes to szSystemDirectory variable, but final result always like this:

\

How solve?

thank you by any help or suggestion.

Upvotes: 0

Views: 2039

Answers (2)

Rudolfs Bundulis
Rudolfs Bundulis

Reputation: 11944

Not sure if the "two slashes" thing is not just something you see in the debugger (since it would show a single slash as an escaped one) but - the biggest issue you have is that your are overwriting the contents of szSystemDirectory with the _stprintf call. I guess what you wanted was to print the \ character at the end of the path. Try

TCHAR szSystemDirectory[MAX_PATH + 2]; // 1 for null terminator, 1 for the slash
UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
szSystemDirectory[nCharactersWritten] = _T('\\');
szSystemDirectory[nCharactersWritten + 1] = _T('\0');

or for two slashes:

TCHAR szSystemDirectory[MAX_PATH + 3]; // 1 for null terminator, 2 for the slashes
UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
szSystemDirectory[nCharactersWritten] = _T('\\');
szSystemDirectory[nCharactersWritten + 1] = _T('\\');
szSystemDirectory[nCharactersWritten + 2] = _T('\0');

_stprint_f has been declared deprecated in Visual Studio 2015, so if you want to use the printing functions you can try:

TCHAR szSystemDirectory[MAX_PATH + 2]; // 1 for null terminator, 1 for the slash
UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
_stprintf_s(szSystemDirectory + nCharactersWritten, MAX_PATH + 2 - nCharactersWritten, _T("%s"), _T("\\")); 

or for two slashes

TCHAR szSystemDirectory[MAX_PATH + 3]; // 1 for null terminator, 2 for the slashes
UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
_stprintf_s(szSystemDirectory + nCharactersWritten, MAX_PATH + 3 - nCharactersWritten, _T("%s"), _T("\\\\"));

Upvotes: 1

Jason
Jason

Reputation: 1099

\ is the escape character. e.g. "\n" codes a newline. What that means is that \ always indicates that the next character is to be treated as a special character. So when you want to tell the compiler that you want a literal \ character you need to escape it the same way:

\\ codes a single \

\\\\ codes double slashes

Upvotes: 1

Related Questions