简体   繁体   English

打印并扫描字符串c

[英]print and scan a string c

I wanted to scan and print a string in C using Visual Studio. 我想使用Visual Studio在C中扫描和打印字符串。

#include <stdio.h>

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

After I did this, it doesn't print the name. 在我这样做之后,它不打印名称。 What could it be? 会是什么呢?

Quoting from the documentation of scanf_s , 引用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 [] . scanfwscanf不同, scanf_swscanf_s要求为所有包含在[] cCsS或字符串控件集的输入参数指定缓冲区大小。 The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable. 字符的缓冲区大小作为附加参数传递,紧跟在指向缓冲区或变量的指针之后。

So, the scanf_s 所以, scanf_s

scanf_s("%s", &name);

is wrong because you did not pass a third argument denoting the size of the buffer. 是错误的,因为你没有传递表示缓冲区大小的第三个参数。 Also, &name evaluates to a pointer of type char(*)[20] which is different from what %s in the scanf_s expected( char* ). 此外, &name计算为char(*)[20]类型的指针,该指针与scanf_s期望值( char* )中的%s不同。

Fix the problems by using a third argument denoting the size of the buffer using sizeof or _countof and using name instead of &name : 通过使用sizeof_countof使用表示缓冲区大小的第三个参数并使用name而不是&name来修复问题:

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

or 要么

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

name is the name of an array and the name of an array "decays" to a pointer to its first element which is of type char* , just what %s in the scanf_s expected. name是数组的名称,数组的名称“衰减”到指向其第一个元素的指针,该元素的类型为char* ,只是scanf_s预期的%s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM