I've been trying to look for answer myself, but I can't find one.
I want to insert a part of the programming that reads in a string like "Hello" and stores and can display it when I want, so that printf("%s", blah);
produces Hello
.
Here's the code part that's giving me trouble
char name[64];
scanf_s("%s", name);
printf("Your name is %s", name);
I know that printf
isn't the problem; the program crashes after something is input after a prompt. Please help?
From the specification of fscanf_s()
in Annex K.3.5.3.2 of the ISO/IEC 9899:2011 standard:
The
fscanf_s
function is equivalent tofscanf
except that thec
,s
, and[
conversion specifiers apply to a pair of arguments (unless assignment suppression is indicated by a*
). The first of these arguments is the same as forfscanf
. That argument is immediately followed in the argument list by the second argument, which has typersize_t
and gives the number of elements in the array pointed to by the first argument of the pair. If the first argument points to a scalar object, it is considered to be an array of one element.
and:
The
scanf_s
function is equivalent tofscanf_s
with the argumentstdin
interposed before the arguments toscanf_s
.
MSDN says similar things (scanf_s()
and fscanf_s()
).
Your code doesn't provide the length argument, so some other number is used. It isn't determinate what value it finds, so you get eccentric behaviour from the code. You need something more like this, where the newline helps ensure that the output is actually seen.
char name[64];
if (scanf_s("%s", name, sizeof(name)) == 1)
printf("Your name is %s\n", name);
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