VS2017中的问题

img

#include<stdio.h>
int main()
{
int ret = 0;
char password[20] = {0};
printf("请输入密码:>");
scanf("%s", password);
printf("请确认Y/N:>");
ret = getchar();
if (ret == 'Y')
{
printf("确认成功\n");
}
else
{
printf("放弃确认\n");
}
return 0;
}

想问问大家为什么VS2017编译的时候 老是报错scanf不安全 ,换成scanf_s编译的结果跳出不来请确认 随便输入密码按回车键直接变成按任意键退出

因为scanf的确不安全,使用scanf可能会造成缓冲区溢出。
scanf和scanf_s使用方法不一样。scanf_s读取字符串时,后面要带缓冲区大小参数。

// 使用scanf读字符串
scanf("%s", password);
// 使用scanf_s读字符串
scanf_s("%s", password, sizeof(password));

完整代码:

#include<stdio.h>
int main()
{
    int ret = 0;
    char password[20] = { 0 };
    printf("请输入密码:>");
    scanf_s("%s", password, sizeof(password));
    printf("请确认Y/N:>");
    getchar();
    ret = getchar();
    if (ret == 'Y')
    {
        printf("确认成功\n");
    }
    else
    {
        printf("放弃确认\n");
    }
    return 0;
}

代码开头加入
#pragma warning(disable:4996)
或者
#define _CRT_SECURE_NO_WARNINGS
取消这个警告。