I know that %s is a string of characters, but I don't know how to use it. Can anyone provide me a very basic example of how its used and how its different from char ?
(edited)
i'm 2 weeks into this course, it's my first time programming. I'm not allowed to use material that hasn't been taught yet on the assignments, so that's why I asked. I have a few books on C and have googled but still wasn't sure, so I asked. (thanks for all the down-votes) All the examples given below use arrays which hasn't been taught yet, so I'm assuming I can't use %s yet either. Thanks.
For both *printf
and *scanf
, %s
expects the corresponding argument to be of type char *
, and for scanf
, it had better point to a writable buffer (i.e., not a string literal).
char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";
printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);
scanf("%55s", str_buf);
Using %s
in scanf
without an explcit field width opens the same buffer overflow exploit that gets
did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf
will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf
, you can't supply the field with as a run time argument:
printf("%*s\n", field_width, string);
One option is to build the format string dynamically:
char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"
EDIT
Using scanf
with the %s
conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like
"This is a test"
then scanf("%55s", str_buf)
will read and assign "This"
to str_buf
. Note that the field with specifier doesn't make a difference in this case.
Here goes:
char str[] = "This is the end";
char input[100];
printf("%s\n", str);
printf("%c\n", *str);
scanf("%99s", input);
%s will get all the values until it gets NULL i.e. '\0'.
char str1[] = "This is the end\0";
printf("%s",str1);
will give
This is the end
char str2[] = "this is\0 the end\0";
printf("%s",str2);
will give
this is
void myfunc(void)
{
char* text = "Hello World";
char aLetter = 'C';
printf("%s\n", text);
printf("%c\n", aLetter);
}
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