windows 是否有格式说明符始终表示带有 _tprintf 的字符字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5669173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a format specifier that always means char string with _tprintf?
提问by hippietrail
When you build an app on Windows using TCHAR
support, %s
in _tprintf()
means char *
string for Ansi builds and wchar_t *
for Unicode builds while %S
means the reverse.
当您使用TCHAR
支持在 Windows 上构建应用程序时,%s
in_tprintf()
表示char *
Ansi 构建和wchar_t *
Unicode 构建的字符串,而%S
反之亦然。
But are there any format specifiers that always mean char *
string no matter if it's an Ansi or Unicode build? Since even on Windows UTF-16 is not really used for files or networking it turns out to still be fairly often that you'll want to deal with byte-based strings regardless of the native character type you compile your app as.
但是,是否有任何格式说明符始终表示char *
字符串,无论它是 Ansi 还是 Unicode 版本?由于即使在 Windows 上,UTF-16 也没有真正用于文件或网络,因此无论您编译应用程序的本机字符类型如何,您仍然需要处理基于字节的字符串。
采纳答案by Remy Lebeau
The h
modifier forces both %s
and %S
to char*
, and the l
modifier forces both to wchar_t*
, ie: %hs
, %hS
, %ls
, and %lS
.
该h
修改的力和%s
与%S
以char*
和l
修改势力既 wchar_t*
,即:%hs
,%hS
,%ls
,和%lS
。
回答by RKum
This might also solve your problem:
这也可能解决您的问题:
_TCHAR *message;
_tprintf(_T("\n>>>>>> %d") TEXT(" message is:%s\n"),4,message);
回答by KungPhoo
I found, that '_vsntprintf_s' uses '%s' for type TCHAR and works for both, GCC and MSVC. So you could wrap it like:
我发现,'_vsntprintf_s' 使用 '%s' 作为 TCHAR 类型并且适用于 GCC 和 MSVC。所以你可以像这样包装它:
int myprintf(const TCHAR* lpszFormat, va_list argptr) {
int len = _vsctprintf(lpszFormat, argptr); // -1:err
if (len<=0) {return len;}
auto* pT = new TCHAR[2 + size_t(len)];
_vsntprintf_s(pT, (2+len)*sizeof(TCHAR), 1+len, lpszFormat, argptr);
int rv = printf("%ls", pT);
delete[] pT;
return rv;
}
int myprintf(const TCHAR* lpszFormat, ...) {
va_list argptr;
va_start(argptr, lpszFormat);
int rv = myprintf(lpszFormat, argptr);
va_end(argptr);
return rv;
}
int main(int, char**) { return myprintf(_T("%s"), _T("Test")); }
回答by Matteo Italia
You can easily write something like this:
你可以很容易地写出这样的东西:
#ifdef _UNICODE
#define PF_ASCIISTR "%S"L
#define PF_UNICODESTR "%s"L
#else
#define PF_ASCIISTR "%s"
#define PF_UNICODESTR "%S"
#endif
and then you use the PF_ASCIISTR
or the PF_UNICODESTR
macros in your format string, exploiting the C automatic string literals concatenation:
然后在格式字符串中使用PF_ASCIISTR
或PF_UNICODESTR
宏,利用 C 自动字符串文字连接:
_tprintf(_T("There are %d ") PF_ASCIISTR _T(" over the table"), 10, "pens");