为什么我不能输入值?

Why can't I input values?

即使代码正确,我也无法在不弹出错误的情况下输入值。

#include <stdio.h>

int main()
{
    char name[100];
    printf("Enter your name: ");
    scanf_s("%s", name);
    printf("Your Name is: %s", name);
    return 0;
}

我在名称中输入一个值并按回车键后,立即弹出一条错误消息并显示:

Unhandled exception at 0x0FC13FD4 (msvcr120d.dll) in Project8.exe: 0xC0000005: Access violation writing location 0x00D40000.

是什么原因造成的,如何解决?

试试这个

if (scanf_s("%99s", name, _countof(name)) == 1)
    printf("Your Name is: %s", name);

两件事

  1. scanf_s() 是缓冲区溢出安全函数,它需要 "%s" 说明符的长度参数。

  2. 如果您确实成功扫描了值,您应该只继续 printf(),检查 (scanf(...) == 1) 在那里。

    那里的1,表示指定符匹配的输入参数之一,因为在这种情况下只有一个,则表示完全匹配。

此外,我几乎可以肯定 _countof() 宏被定义为 sizeof(x) / sizeof(x[0]) 所以这也应该如此

if (scanf_s("%99s", name, sizeof(name)) == 1)
    printf("Your Name is: %s", name);

因为在这种情况下 sizeof(name[0]) == sizeof(char) == 1

如果您使用标准 scanf() 函数,即

,您的代码就可以运行
if (scanf("%99s", name) == 1)
    printf("Your Name is: %s", name);

您应该使用 fgets 而不是

#include <stdio.h>

int main(void)
{
    char name[100];
    printf("Enter your name: ");

    if (fgets(name, sizeof(name), stdin) == NULL)
        return 1;

    printf("Your Name is: %s", name);
    return 0;
}