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 it’s different from char?
All the examples given below use arrays which hasn’t been taught yet, so I’m assuming I can’t use %s yet either.
For both
*printfand*scanf,%sexpects the corresponding argument to be of typechar *, and forscanf, it had better point to a writable buffer (i.e., not a string literal).Using
%sinscanfwithout an explcit field width opens the same buffer overflow exploit thatgetsdid; namely, if there are more characters in the input stream than the target buffer is sized to hold,scanfwill happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike inprintf, you can’t supply the field with as a run time argument:One option is to build the format string dynamically:
EDIT
Using
scanfwith the%sconversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks likethen
scanf("%55s", str_buf)will read and assign"This"tostr_buf. Note that the field with specifier doesn’t make a difference in this case.