printf的,wprintf%S%S,%LS,char *与WCHAR *:错误不是由编译器警告公布? [英] printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

查看:1190
本文介绍了printf的,wprintf%S%S,%LS,char *与WCHAR *:错误不是由编译器警告公布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试以下code:

  wprintf(L1%S \\ n,一些字符串); //好
wprintf(L2%S \\ n,L一些字符串); //不好 - >打印字符串只有第一个字符
的printf(3%S \\ n,一些字符串); //好
//输出(4%S \\ n,L一些字符串); //不能编译
的printf(\\ n);
wprintf(L1%S \\ n,一些字符串); //不好 - >打印一些有趣的东西
wprintf(L2%S \\ n,L一些字符串); //好
//的printf(3%S \\ n,一些字符串); //不能编译
的printf(4%S \\ n,L一些字符串); //好

和我得到以下的输出:

  1一些字符串
2秒
3一些字符串1 G1%S2一些字符串
4一些字符串

所以说:看来这两个 wprintf 的printf 能够正确打印都一个char *和WCHAR *,但仅在使用的确切说明符。 如果使用了错误的说明,你可能无法得到一个编译错误(也警告!)和错误的行为而告终。您是否遇到相同的行为?

请注意:这是Windows下的测试,与MinGW和编制的 G ++ 4.7.2(我会检查GCC版本)

编辑:我也试过%1!(结果是评论)

 的printf(\\ n);
wprintf(L1%2!\\ n,一些字符串); //不好 - >打印有趣的东西
wprintf(L2%1!\\ n,L一些字符串); //好
//输出(3%LS \\ n,一些字符串); //不能编译
的printf(4%LS \\ n,L一些字符串); //好


解决方案

我怀疑GCC(MinGW的)定制code禁用检查宽的printf 在Windows功能。这是因为微软自己的实现(MSVCRT)是的严重错误的并具有%S %1! 向后作为广的printf 功能;因为GCC不能确定你是否将与MS的破实施或纠正一些之一进行连接,它至少可以做的,突兀的事情只是关闭警告。

I have tried the following code:

wprintf(L"1 %s\n","some string"); //Good
wprintf(L"2 %s\n",L"some string"); //Not good -> print only first character of the string
printf("3 %s\n","some string"); //Good
//printf("4 %s\n",L"some string"); //Doesn't compile
printf("\n");
wprintf(L"1 %S\n","some string"); //Not good -> print some funny stuff
wprintf(L"2 %S\n",L"some string"); //Good
//printf("3 %S\n","some string"); //Doesn't compile
printf("4 %S\n",L"some string");  //Good

And I get the following output:

1 some string
2 s
3 some string

1 g1 %s

2 some string
4 some string

So: it seems that both wprintf and printf are able to print correctly both a char* and a wchar*, but only if the exact specifier is used. If the wrong specifier is used, you might not get a compiling error (nor warning!) and end up with wrong behavior. Do you experience the same behaviour?

Note: This was tested under Windows, compiled with MinGW and g++ 4.7.2 (I will check gcc later)

Edit: I also tried %ls (result is in the comments)

printf("\n");
wprintf(L"1 %ls\n","some string"); //Not good -> print funny stuff
wprintf(L"2 %ls\n",L"some string"); //Good
// printf("3 %ls\n","some string"); //Doesn't compile
printf("4 %ls\n",L"some string");  //Good

解决方案

I suspect GCC (mingw) has custom code to disable the checks for the wide printf functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s and %ls backwards for the wide printf functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.

这篇关于printf的,wprintf%S%S,%LS,char *与WCHAR *:错误不是由编译器警告公布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆