6

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?

4
  • do you enter a name at command promt ?.. as by looking at the code, everything seems good Commented Apr 14, 2015 at 14:12
  • Yes, if I type my name, it doesn't write anything as output. Commented Apr 14, 2015 at 14:13
  • Does Visual Studio give a warning about scanf_s("%s", name);? What version are you using? Commented Apr 14, 2015 at 16:08
  • I already fixed it with: scanf_s("%s", name, sizeof(name)); Commented Apr 14, 2015 at 21:18

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.