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也有正确赋值。
第二次输入看起来像是无效输入?
如果在格式字符串(出现了空白字符(空格、\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