使用C scanf_s的字符串输入

use*_*529 3 c string scanf tr24731 c11

我一直在寻找自己的答案,但找不到。我想插入一部分程序,该程序读取“ Hello”之类的字符串并存储并在需要时显示它,从而printf("%s", blah);产生Hello

这是给我麻烦的代码部分

char name[64];
scanf_s("%s", name);
printf("Your name is %s", name);
Run Code Online (Sandbox Code Playgroud)

我知道那printf不是问题;在提示后输入内容后,程序崩溃。请帮忙?

Jon*_*ler 5

根据fscanf_s()ISO / IEC 9899:2011标准的附件K.3.5.3.2的规范:

fscanf_s功能相当于fscanf不同之处在于cs[转换说明适用于对参数(除非分配抑制由指示 *)。这些参数中的第一个与for相同fscanf。该参数在参数列表中紧随其后,第二个参数具有类型, rsize_t并给出该对中第一个参数所指向的数组中的元素数。如果第一个参数指向标量对象,则将其视为一个元素的数组。

和:

scanf_s函数等效于fscanf_s在的参数stdin 之前插入参数scanf_s

MSDN说类似的话(scanf_s()fscanf_s())。

您的代码未提供length参数,因此使用了其他一些数字。它并不确定所能找到的价值,因此您会从代码中得到古怪的行为。您需要更多类似的内容,其中的换行符可帮助确保实际看到输出。

char name[64];
if (scanf_s("%s", name, sizeof(name)) == 1)
    printf("Your name is %s\n", name);
Run Code Online (Sandbox Code Playgroud)


小智 5

我在大学课程中经常使用它,因此它在 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()
Run Code Online (Sandbox Code Playgroud)

参考: https: //msdn.microsoft.com/en-us/library/w40768et.aspx


M-N*_*M-N -1

你应该做这个 :scanf ("%63s", name);

更新

下面的代码对我有用:

#include <stdio.h> 
int main(void) { 
    char name[64]; 
    scanf ("%63s", name); 
    printf("Your name is %s", name); 
    return 0; 
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Visual Studio,请单击“Project properties -> Configuration Properties -> C/C++-> Preprocessor -> Preprocessor Definitions添加edit”,然后_CRT_SECURE_NO_WARNINGS单击“确定”,应用设置并再次运行。

注意:只有当您正在做作业或类似的事情时,这才有用,不建议在生产中使用。