我一直试图自己寻找答案,但我找不到。我想插入编程的一部分,它读取像“Hello”这样的字符串并存储并可以在我想要的时候显示它,这样就可以printf("%s", blah);
生成Hello
.
这是给我带来麻烦的代码部分
char name[64];
scanf_s("%s", name);
printf("Your name is %s", name);
我知道那printf
不是问题;在提示后输入某些内容后程序崩溃。请帮忙?
根据fscanf_s()
ISO/IEC 9899:2011 标准附录 K.3.5.3.2 中的规范:
该
fscanf_s
函数等价于,fscanf
除了c
,s
和[
转换说明符适用于一对参数(除非赋值抑制由 a 指示*
)。这些参数中的第一个与 for 相同fscanf
。该参数在参数列表中紧随其后的是第二个参数,它具有类型rsize_t
并给出数组中由该对的第一个参数指向的元素的数量。如果第一个参数指向一个标量对象,它被认为是一个元素的数组。
和:
该
scanf_s
函数等效于fscanf_s
在 的参数stdin
之前插入参数scanf_s
。
MSDN 说了类似的话(scanf_s()
和fscanf_s()
)。
您的代码没有提供长度参数,因此使用了其他数字。它不确定它找到什么值,所以你会从代码中得到古怪的行为。您需要更多类似的东西,换行有助于确保实际看到输出。
char name[64];
if (scanf_s("%s", name, sizeof(name)) == 1)
printf("Your name is %s\n", name);
我在大学课程中经常使用它,所以这在 Visual Studio 中应该可以正常工作(在 VS2013 中测试):
char name[64]; // the null-terminated string to be read
scanf_s("%63s", name, 64);
// 63 = the max number of symbols EXCLUDING '\0'
// 64 = the size of the string; you can also use _countof(name) instead of that number
// calling scanf_s() that way will read up to 63 symbols (even if you write more) from the console and it will automatically set name[63] = '\0'
// if the number of the actually read symbols is < 63 then '\0' will be stored in the next free position in the string
// Please note that unlike gets(), scanf() stops reading when it reaches ' ' (interval, spacebar key) not just newline terminator (the enter key)
// Also consider calling "fflush(stdin);" before the (eventual) next scanf()
你应该做这个 :scanf ("%63s", name);
更新:
下面的代码对我有用:
#include <stdio.h>
int main(void) {
char name[64];
scanf ("%63s", name);
printf("Your name is %s", name);
return 0;
}
如果您使用的是 Visual Studio,请Project properties -> Configuration Properties -> C/C++-> Preprocessor -> Preprocessor Definitions
单击edit
并添加_CRT_SECURE_NO_WARNINGS
单击确定,应用设置并再次运行。
注意:这仅在您正在做作业或类似的事情时才有用,并且不建议用于生产。
#include<stdio.h>
int main()
{
char name[64];
printf("Enter your name: ");
scanf("%s", name);
printf("Your name is %s\n", name);
return 0;
}
#include<stdio.h>
int main()
{
char name[64];
printf("Enter your name: ");
gets(name);
printf("Your name is %s\n", name);
return 0;
}