c++ - 使用字符数组调用 scanf_s()

标签 c++ arrays scanf

我试过这段代码,但它不起作用。

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/

相关文章:

c++ - Windows网络包修改

c++ - 大QImage的问题

c - 如何在C中按升序对字符串数组进行排序

c - 底数大于10的C扫描

c - 在循环中对带空格的字符串使用 scanf 时的有趣行为

c - 逐行读取的 shell

c++ - 为什么在 extern "C"中定义了 __cplusplus

c++ - 循环与 float 迭代

python - 从较小的矩阵填充较大的矩阵

c - 如何用C语言对两个100位数字进行加、减、乘、除运算? (使用数组)