【问题标题】:How concatenate a TCHAR array with a string?如何连接一个 TCHAR 数组和一个字符串?
【发布时间】:2017-03-09 21:55:04
【问题描述】:

我有以下代码:

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

AfxMessageBox(szSystemDirectory);

并希望将两个斜杠连接到 szSystemDirectory 变量,但最终结果总是这样:

\

如何解决?

感谢您的任何帮助或建议。

【问题讨论】:

  • 为什么不直接使用字符串类?
  • You've run up against escape characters. TLDR; '\' 有特殊含义。 "\\" 是一个斜线。如果你想要两个,你必须使用 4: "\\\\"
  • TCHAR 不是真正的类型;它是一个 #define ,根据是否设置了 UNICODE 标志,它被设置为 CHAR 或 WCHAR。没有真正的理由再使用它了,事实上,如果没有设置 UNICODE 标志,您的代码将无法工作,因为您可以互换使用 _T()L 宏。

标签: c++ visual-c++ tchar


【解决方案1】:

不确定“两个斜杠”是否不仅仅是您在调试器中看到的东西(因为它会显示一个单斜杠作为转义斜杠)但是 - 您遇到的 最大 问题是您正在使用 _stprintf 调用覆盖 szSystemDirectory 的内容。我猜你想要的是在路径末尾打印\ 字符。试试

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');

或两个斜杠:

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

或两个斜线

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

【讨论】:

    【解决方案2】:

    \ 是转义字符。例如"\n" 编码换行符。这意味着 \ 始终表示下一个字符将被视为特殊字符。因此,当您想告诉编译器您想要一个 literal \ 字符时,您需要以相同的方式对其进行转义:

    \\ codes a single \
    
    \\\\ codes double slashes
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2022-12-17
      • 1970-01-01
      • 2015-05-02
      • 2016-08-08
      • 2013-05-15
      • 1970-01-01
      • 2018-10-15
      相关资源
      最近更新 更多