scanf 的“正则表达式”是吗?支持标准吗?
scanf 的“正则表达式”支持是标准吗?我在任何地方都找不到答案。
此代码在 gcc 中有效,但在 Visual Studio 中无效:
scanf("%[^\n]",a);
这是 Visual Studio 错误还是 gcc 扩展?
编辑:看起来 VS 可以工作,但必须考虑 Linux 和 Windows 之间行结束的差异。(\r\n)
Is scanf's "regex" support a standard? I can't find the answer anywhere.
This code works in gcc but not in Visual Studio:
scanf("%[^\n]",a);
It is a Visual Studio fault or a gcc extension ?
EDIT: Looks like VS works, but have to consider the difference in line ends between Linux and Windows.(\r\n)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该特定格式字符串应该在一致的实现中正常工作。
[
字符引入一个扫描集,用于匹配非空字符集(^
表示扫描集是所提供字符的反转)。换句话说,格式说明符%[^\n]
应匹配每个非换行符。来自 C99 7.19.6.2,稍作解释:
如果 MSVC 无法正常工作,这可能只是 Microsoft 不符合最新标准或认为自己更了解的众多示例之一:-)
That particular format string should work fine in a conforming implementation. The
[
character introduces a scanset for matching a non-empty set of characters (with the^
meaning that the scanset is an inversion of the characters supplied). In other words, the format specifier%[^\n]
should match every character that's not a newline.From C99 7.19.6.2, slightly paraphrased:
It's possible, if MSVC isn't working correctly, that this is just one of the many examples where Microsoft either don't conform to the latest standard, or think they know better :-)
scanf()
的"%["
格式规范是标准的,自 C90 以来一直如此。MSVC 确实支持它。
您还可以在格式规范中提供字段宽度,以防止缓冲区溢出:
另请注意,
"%["
格式规范并不意味着scanf()
支持正则表达式。该特定格式规范类似于正则表达式的功能(毫无疑问受到正则表达式的影响),但它比正则表达式受到更多限制。The
"%["
format spec forscanf()
is standard and has been since C90.MSVC does support it.
You can also provide a field width in the format spec to provide safety against buffer overruns:
Also note that the
"%["
format spec doesn't mean thatscanf()
supports regular expressions. That particular format spec is similar to a capability of regexs (and no doubt was an influenced by regex), but it's far more limited than regular expressions.