Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 667
TheWitcher Avatar asked Apr 14 '15 14:04

TheWitcher


People also ask

Can you scan a string in C?

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.).

How do you print string in C?

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);


1 Answers

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.

like image 76
Spikatrix Avatar answered Oct 30 '22 23:10

Spikatrix