简体   繁体   English

如何将TCHAR数组与字符串连接?

[英]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: 并希望将两个斜杠连接到szSystemDirectory变量,但最终结果始终像这样:

\\ \\

How solve? 怎么解决?

thank you by any help or suggestion. 谢谢您的帮助或建议。

\\ is the escape character. \\是转义字符。 eg "\\n" codes a newline. 例如,“ \\ n”编码换行符。 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

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. 不知道“两个斜杠”是否不仅是在调试器中看到的(因为它将显示一个斜杠作为转义的斜杠),而是-您遇到的最大问题是您正在用_stprintf覆盖szSystemDirectory的内容呼叫。 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: _stprint_f已在Visual Studio 2015中声明为已弃用,因此,如果要使用打印功能,可以尝试:

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("\\\\"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM