c - 打印并扫描字符串 c

标签 c string char printf

我想使用 Visual Studio 在 C 中扫描并打印一个字符串。

#include <stdio.h>

main() {
    char name[20];
    printf("Name: ");
    scanf_s("%s", name);
    printf("%s", name);
}

在我这样做之后,它不会打印名称。 会是什么?

最佳答案

引自the documentation of scanf_s ,

Remarks:

[...]

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", &name);

是错误的,因为您没有传递表示缓冲区大小的第三个参数。另外,&name求值为 char(*)[20] 类型的指针这与 %s 不同在scanf_s预期( char* )。

通过使用表示缓冲区大小的第三个参数来解决问题 sizeof_countof并使用 name而不是 &name :

scanf_s("%s", name, sizeof(name));

scanf_s("%s", name, _countof(name));

name是数组的名称,数组的名称“衰减”到指向其第一个元素的指针,该元素的类型为 char* ,到底是什么 %sscanf_s预期。

关于c - 打印并扫描字符串 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29629531/

相关文章:

C 编程写入注册表不起作用? RegSetValueEX 错误

c程序需要找错吗?

c - sprintf 中未获取任何数据

c - 用C语言快速排序对字符串进行排序

c - 如何使用 GNU getopt 获取输入参数的长度

python - 将字符串列表与字符串列表进行比较(python)

java - 字符串和字符的连接

c++ - 交换 C++ 数组的 2 个字符

java - 如何在不使用 Java 中的 Replace() 的情况下替换字符串中的字符?

c - memset 函数的正确类型是什么?