刚入门新ren提问:
⟪C Primer Plus⟫书中的第64页的下面这项程序清单,在Visual Studio 2022上面写的时候出问题了(╯°□°)╯︵ ┻━┻
#include<stdio.h>
#include<string.h>
#define PRAISE "You are an extraordinary being."
int main(void)
{
char name[40];
printf("What's your name?");
scanf_s("%s", name);
printf("Hello, %s. %s\n", name, PRAISE);
printf("Your name of %zd letters occupies %zd memory cells.\n",
strlen(name),sizeof name);
printf("The phrase of praise has %zd letters", strlen(PRAISE));
printf("and occupies %zd meory cells.\n", sizeof PRAISE);
return 0;
}
第9行改这样
scanf_s("%s",name,40);
scanf_s()函数:
scanf_s() 的功能虽然与scanf() 相同,但却比 scanf() 安全,因为 scanf_s() 是针对“ scanf()在读取字符串时不检查边界,可能会造成内存泄露”这个问题设计的。
scanf_s()用于读取字符串时,必须提供一个数字以表明最多读取多少位字符,以防止溢出。
scanf_s("%s", name);
->
scanf_s("%s", name, 40);
vs2022启用安全函数以后是要求你用scanf_S的时候传一个字符串的长度参数,这个软件开发文档不是有写吗?
https://ask.csdn.net/questions/7822006
你看这个链接?一模一样的问题
第9行: scanf_s("%s", name); 输入语句两个问题,一是scanf_s()函数不接受空格,所以输入 Serendipity Chance 时读取成功只能读到 Serendipity ,二是scanf_s()函数,参数后面需加一个参数大小值。结合以上两点,这句修改为:scanf_s("%[^\n]", name, 40);
int main()
{
char a = 0;
scanf_s("%c", &a, sizeof(a));
return 0;
}
scanf_s("%s", name);问题是在这一行,首先,scanf_s()函数是无法读取空格所以后面的 Chance 读取不到,其次scanf_s()函数,参数后面需加一个参数大小值。
这句修改为:scanf_s("%[^\n]", name, 40);就没问题了。
用这个scanf_s("%s", name, 40);
【以下回答由 GPT 生成】
由于 Visual Studio 2022 是较新的版本,与较旧的版本存在一些差异。在你的情况下,问题可能与 scanf_s
函数有关。在 Visual Studio 2022 中,scanf_s
函数要求传入字符数组的大小参数。解决方法如下:
scanf_s
的参数修改为 %s
,并在其后传入 name
数组的大小。代码如下所示:scanf_s("%s", name, sizeof(name));
<stdlib.h>
或 <wchar.h>
。这些头文件在一些编译器中可能没有隐式包含。你可以在代码中添加以下行来确保这些头文件已经被包含:#include <stdlib.h>
或者
#include <wchar.h>
使用上述方法更新后的代码应如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // 或 #include <wchar.h>
#define PRAISE "You are an extraordinary being."
int main(void)
{
char name[40];
printf("What's your name?");
scanf_s("%s", name, sizeof(name));
printf("Hello, %s. %s\n", name, PRAISE);
printf("Your name of %zd letters occupies %zd memory cells.\n",
strlen(name), sizeof name);
printf("The phrase of praise has %zd letters and occupies %zd memory cells.\n",
strlen(PRAISE), sizeof PRAISE);
return 0;
}
我希望这些解决方案能够解决你遇到的问题。如果问题仍然存在,请提供更多详细信息,以便我能够提供更准确的帮助。