scanf_s函数有时会有两次输入

本文讨论了在使用scanf_s函数时遇到的输入问题,即有时会要求输入两次值。分析了原因在于格式字符串中的空白字符。解决方案是简化scanf_s的使用,避免空白字符,以免造成不必要的输入混乱。通过示例代码展示了问题及解决方法。
摘要由CSDN通过智能技术生成

scanf_s函数有时会有两次输入

在使用scanf_s函数时,发现一个现象,在输入时会对同一个变量输入两次值
代码如下:

#include<stdio.h>

int main()
{
	int x;
	printf_s("scanf_s double input same val \n");
	printf_s("this is scanf_s :");
	scanf_s("%d \n",&x);
	printf_s("this is printf %d", x);
	return 0;
}

运行结果:

scanf_s double input same val
this is scanf_s :1
2
this is printf 1
D:\File\code\C\C_Project\ProjectTrain\Debug\ProjectTrain.exe (进程 29516)已退出 ,返回代码为: 0。
按任意键关闭此窗口...

看起来第一次输入是正确输入的,x也有正确赋值。
第二次输入看起来像是无效输入?

从网上查了下scanf造成的原因

如果在格式字符串(出现了空白字符(空格、\n、\t之类),那么 scanf() 会吃掉输入中所有接下来的空白字符。
去掉\n:

故意手动打空格:

#include<stdio.h>

int main()
{
	int x;
	printf_s("scanf_s double input same val \n");
	printf_s("this is scanf_s :");
	scanf_s("%d",&x);
	printf_s("this is printf %d", x);
	return 0;
}
scanf_s double input same val
this is scanf_s :1 2

 this is printf 1
D:\File\code\C\C_Project\ProjectTrain\Debug\ProjectTrain.exe (进程 35456)已退出 ,返回代码为: 0。
按任意键关闭此窗口...

在scanf后加空格:

#include<stdio.h>

int main()
{
	int x;
	printf_s("scanf_s double input same val \n");
	printf_s("this is scanf_s :");
	scanf_s("%d ",&x);
	printf_s("this is printf %d" , x;
	return 0;
}

效果和之前相同

scanf_s double input same val
this is scanf_s :1
2
this is printf 1
D:\File\code\C\C_Project\ProjectTrain\Debug\ProjectTrain.exe (进程 30824)已退出 ,返回代码为: 0。
按任意键关闭此窗口...

解决方式:
在scanf的使用过程中,尽量简洁,不要去使用空白字符,空白字符的使用可以交给prinf

感谢:

https://blog.csdn.net/qq_46527915/article/details/104952546

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值