Reputation: 2039
I want to read a string
using scanf
and get the actual str length and then realloc
it afterward. I've read that %n
gives the number of chars read
, so that's what I need. Visual Studio asks me to use scanf_s
, where after each string you must specify it's buffer size.
I write:
int actual_length;
scanf_s("%[^\n]s%n", str, MAX_STRING_LEN, &actual_length);
printf("actual length = %d\n", actual_length);
I get:
actual length = -858993460
So, when I added this %n
nothing happened. If I take away just the%n
it says too many args, if I take away just the &actual_length
it says too few args. If I take away both the result is the same, obviously.
I tried to google for like 40 mins and I'm stuck. MSDN doesn't say anything specific about scanf_s treating %n
.
Upvotes: 3
Views: 157
Reputation: 2039
BLUEPIXY answered this question in the comments:
"%[^\n]s%n
" --> "%[^\n]%n
"
In this case, s
is not correct. s
is a designation that it isn't conversion specifier. It is interpreted as a matched character. However, since matching characters do not actually exist, Input will fail at s
. So %n
is not interpreted.
Upvotes: 2