是否有格式说明符始终表示使用_tprintf的字符串?

时间:2011-04-14 20:20:03

标签: windows printf tchar format-specifiers

使用TCHAR支持在Windows上构建应用时,%s中的_tprintf()表示Ansi版本的char *字符串,而wchar_t *代表%S {1}}意味着相反。

但是有没有格式说明符总是意味着char *字符串,无论它是Ansi还是Unicode构建?因为即使在Windows上,UTF-16并不真正用于文件或网络,但事实上你仍然需要处理基于字节的字符串,无论你编译应用程序的本地字符类型如何。

4 个答案:

答案 0 :(得分:5)

h修饰符强制%s%S char*,而l修饰符强制wchar_t*,即:{ {1}},%hs%hS%ls

答案 1 :(得分:1)

这也可以解决您的问题:

_TCHAR *message;
_tprintf(_T("\n>>>>>> %d") TEXT(" message is:%s\n"),4,message);

答案 2 :(得分:0)

您可以轻松地写下这样的内容:

#ifdef _UNICODE
#define PF_ASCIISTR    "%S"L
#define PF_UNICODESTR  "%s"L
#else
#define PF_ASCIISTR    "%s"
#define PF_UNICODESTR  "%S"
#endif

然后在格式字符串中使用PF_ASCIISTRPF_UNICODESTR宏,利用C自动字符串文字连接:

_tprintf(_T("There are %d ") PF_ASCIISTR _T(" over the table"), 10, "pens");

答案 3 :(得分:0)

我发现,'_ vsntprintf_s'对TCHAR类型使用'%s'并适用于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")); }