How can I use a variable to specify the max number of chars scanf()
should read in?
For example using printf()
you can use the * like so
#define MAXVAL 5
printf("Print at maximum MAXVAL chars: %.*s\n", MAXVAL, "myStringHere");
This will only print 5 chars, how can I make scanf
only read in MAXVAL? MAXVAL must be used as the length specifier. I cannot simply do
scanf("%5s", string);
Right now I can only think of reading into a large array using scanf
then using ssprintf
to store the string into my length limited string. Using a length specifier would be so much easier however.
-1
that amount becausescanf
add a NUL character reading for that string(%s
). E.g.scanf("%4s", string);
MAXVAL
instead of hardcoding a value in the format string.fgets
breaks on newlines,scanf
breaks on whitespace. @CSStudent you can create format specifier in code.MAXVAL
scanf()
does not necessarily break on white-space as it depends on the format.scanf("%5s")
will consume leading white-space (not break on w-s), then scan non-white-space characters until 1) white-space (does break on w-s) 2) 5char
read 3) EOF or 4) IOError.