简体   繁体   中英

print and scan a string c

I wanted to scan and print a string in C using Visual Studio.

#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 ,

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.

So, the 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* ).

Fix the problems by using a third argument denoting the size of the buffer using sizeof or _countof and using name instead of &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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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