有什么方法可以在 C 中的 fscanf 中包含原始参数
我想看看当我这样做时
fscanf(inputSTREAM, "$%s$", out)
是否也可以返回 $ 符号 - 有什么办法吗?
I'm trying to see if when I do
fscanf(inputSTREAM, "$%s$", out)
I can also return the $ signs - is there a way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为没有办法使用
scanf()
系列函数检索带有美元符号的字符串以及它们之间的非空白字符串。最接近的方法可能是使用扫描集,但扫描集与正则表达式不同,您需要一个正则表达式来指定您要查找的模式。实际上,您可能可以使用以下方法将第一个美元符号放入字符串中:
即使您知道字符串的确切长度,也无法对后一个美元符号使用相同的特技。问题是您需要用第二个美元符号覆盖字符串末尾的 null,并且您需要在字符串后面有一个 NUL
'\0'
。添加最后一个美元比在字符串的开头插入第一个美元要容易得多。第三个扫描集包含一个赋值抑制“*
”,并且最后需要一美元。格式中的前导空格会跳过空格。这不是保证的行为;第一个转换将在
out[1]
上写入 NUL,第二个转换将在out[1]
上写入字符串,但 C 标准不保证它会起作用的。I don't think there's a way to retrieve the string with the dollar signs and the non-blank string between them using the
scanf()
family of functions. The closest approach would probably be using a scanset, but scansets are not the same as regular expressions, and you'd need a regular expression to specify the pattern you are looking for.In practice, you could probably get the first dollar sign into the string using:
You can't pull the same stunt for the latter dollar sign, even if you know the exact length of the string. The trouble is that you'd need to overwrite the null at the end of the string with the second dollar sign, and you'd want a NUL
'\0'
after the string. Adding the final dollar is much easier than inserting the first at the beginning of the string. The third scanset contains an assignment-suppressing '*
' and requires a dollar at the end. The leading space in the format skips spaces.This isn't guaranteed behaviour; the first conversion would write a NUL over
out[1]
, and the second conversion would then write the string overout[1]
, but the C standard does not guarantee that it will work.请注意,在
"$%s$"
中,第二个美元是无用的,因为%s
表示“非空白字符序列”。因此,%s
已经扫描了终止美元。您所需要做的就是在开头使用%c
扫描初始美元,例如尝试以下操作:请注意
%62s
中的 62 比sizeof 少 2 out
为初始美元留出空间并以 0 结尾。Note that in
"$%s$"
the second dollar is useless, as%s
means "sequence of non-white space characters". So, the terminating dollar is already scanned by the%s
. All you need to do is scan the initial dollar with%c
at the beginning, e.g. try this:Note that 62 in
%62s
is two less than thesizeof out
to leave room for the initial dollar and terminating 0.您可以将该行作为字符串读取,然后使用 sscanf 获取您使用 fscanf 获取的值。然后您将获得原始字符串和 sscanf 的值。
You could read the line as a string, then use sscanf to get the value you're using fscanf for. Then you'll have the original string and the value from sscanf.