当我尝试使用 Scanf 时,它会抛出一个随机异常(scanf_s 也是如此)

Scanf throws a random exception when I try to use it(same for scanf_s)

代码如下:

#include <iostream>
#include <stdio.h>
int main()
{
    char name[15];
    printf_s("What is your name: ");
    scanf_s("%s",name);
    printf_s("Nice to meet you, %s", name);
    return(0);
}

请帮助我知道哪里出了问题。我在 VS2019 中这样做,如果有帮助,我会使用 c++。

您可以只使用 scanf 而不是 scanf_s,要消除错误,您可以在代码顶部写入“#define _CRT_SECURE_NO_WARNINGS”。 scanf 和 scanf_s 的区别在于,在 scanf_s 中,您可以指定缓冲区大小并控制输入的大小以避免崩溃。在这个级别没有必要,但我建议你研究一下。

此外,如果您使用的是 C++,则可以像这样声明字符串:

std::string varName 和 cout/cin 操作在我看来更容易。

 #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
int main()
{
    char name[128];
    printf("What is your name: ");
    scanf("%s", &name);
    printf("Nice to meet you, %s", name);
    return(0);
}

或者更简单的方法:

#include <iostream>
int main()
{
    std::string name;
    std::cout<< "What is your name: ";
    std::cin >> name;
   std::cout << "Nice to meet you, " << name;
   return 0;
}