MSDN的解释为:
The main difference between printf_s and printf is that printf_s checks the format string for valid formatting characters, whereas printf only checks if the format string is a null pointer.
printf只是检查format字符串是否为空。如果为空,会触发assert(false)。
而printf_s还会检查format字符串是否有效,即其中格式是否合法。如果不合法,也会触发assert(false)。
如下代码:
#include <cstdio>
#include <string>
int main()
{
char* format = nullptr;
printf(format, "hello", 10);
return 0;
}
运行结果:
执行如下代码:
#include <cstdio>
#include <string>
int main()
{
char* format = "%s %d %k";
printf_s(format, "hello", 10, 1);
return 0;
}
format格式错误, 因为没有%k这个格式。
另外:
在format字符串格式正确的情况下,
如果参数个数大于需要的个数,多余的参数忽略不处理。
如果是小于,没填参数的位置随机(或者为乱码)。
如下示例:
#include <cstdio>
#include <string>
int main()
{
char* format1 = "%s %d\n";
printf(format1, "hello", 10, 1);
printf_s(format1, "hello", 10, 1);
char* format2 = "%s %d %d %d %s\n";
printf(format2, "hello", 10, 1);
printf_s(format2, "hello", 10, 1);
return 0;
}
输出为: