使用C scanf_s输入字符串

我一直在努力寻找答案,但我找不到答案。 我想插入一个读取字符串的部分,如“Hello”字符串并存储并可以在需要时显示它,以便printf("%s", blah); 产生Hello

这是给我带来麻烦的代码部分

 char name[64]; scanf_s("%s", name); printf("Your name is %s", name); 

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

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

fscanf_s函数等效于fscanf除了cs[转换说明符适用于一对参数(除非赋值抑制由*表示)。 这些参数中的第一个与fscanf相同。 该参数在参数列表中紧跟第二个参数,其类型为rsize_t并给出该对的第一个参数指向的数组中的元素数。 如果第一个参数指向标量对象,则认为它是一个元素的数组。

和:

scanf_s函数等效于fscanf_s ,其参数stdin介于fscanf_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); 

我经常在我的大学课程中使用它,所以这应该在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() 

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

 #include int main() { char name[64]; printf("Enter your name: "); gets(name); printf("Your name is %s\n", name); return 0; } 
  #include int main() { char name[64]; printf("Enter your name: "); scanf("%s", name); printf("Your name is %s\n", name); return 0; } 

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