[英]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. 我想使用
scanf
读取一个string
并获取实际的str长度,然后再重新realloc
它。 I've read that %n
gives the number of chars read
, so that's what I need. 我已经读过
%n
给出了number of chars read
,所以这就是我需要的。 Visual Studio asks me to use scanf_s
, where after each string you must specify it's buffer size. Visual Studio要求我使用
scanf_s
,在每个字符串之后你必须指定它的缓冲区大小。
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. 所以,当我添加这个
%n
没有发生任何事情。 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. 如果我带走了
%n
它会说太多args,如果我带走了&actual_length
那么它说的args太少了。 If I take away both the result is the same, obviously. 如果我带走两者,结果显然是一样的。
I tried to google for like 40 mins and I'm stuck. 我尝试谷歌40分钟,我被卡住了。 MSDN doesn't say anything specific about scanf_s treating
%n
. MSDN没有说明有关scanf_s处理
%n
任何具体信息。
BLUEPIXY answered this question in the comments: BLUEPIXY在评论中回答了这个问题:
" %[^\\n]s%n
" --> " %[^\\n]%n
" “
%[^\\n]s%n
” - >“ %[^\\n]%n
”
In this case, s
is not correct. 在这种情况下,
s
不正确。 s
is a designation that it isn't conversion specifier. s
是一个不是转换说明符的名称。 It is interpreted as a matched character. 它被解释为匹配的角色。 However, since matching characters do not actually exist, Input will fail at
s
. 但是,由于实际上不存在匹配字符,因此输入将在
s
失败。 So %n
is not interpreted. 所以
%n
没有被解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.