我试过这段代码,但它不起作用。
char word1[40];
printf("Enter text: \n");
scanf_s("%s", word1);
printf("word1 = %s", word1);
当我执行它时,它显示:
word1 =
最佳答案
如果您仔细阅读MSDN documentation of scanf_s()
,您会注意到您必须提供字符串缓冲区的长度:
Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.
调整你的scanf_s()
调用如下:
scanf_s("%s", word1, _countof(word1));
这应该有效。
(注意 _countof()
需要包括 <stdlib.h>
。)
关于c++ - 使用字符数组调用 scanf_s(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22024213/