printf_s与printf的异同

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;
} 

输出为:
在这里插入图片描述

  • 10
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值