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?
Read String from the user You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).
using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);
Quoting from the documentation of scanf_s,
Remarks:
[...]
Unlike
scanfandwscanf,scanf_sandwscanf_srequire the buffer size to be specified for all input parameters of typec,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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With