简体   繁体   中英

C: “%n” (number of characters read) gets ignored by scanf_s

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM