sscanf 有多个空格吗?

发布于 2024-09-02 17:16:19 字数 173 浏览 2 评论 0原文

sscanf(文本, "%s %s", 姓名, 公司);

解析 'ian mceknis' 但它也解析 'ian   mceknis' 等等。我怎样才能让它只解析第一个?它必须仅包含一个空格,不能包含更多空格。

谢谢。

sscanf(text, "%s %s", name, company);

parses 'ian mceknis' but it also parses 'ian   mceknis' and so on. How can i make this to parse only the first one? It must contain only one space not more.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

咿呀咿呀哟 2024-09-09 17:16:19

如果您希望它拒绝后一个示例,您必须推出自己的函数来查找/拒绝多个空格。

但我的猜测是,你真正想做的是去掉多余的空格。请参阅:如何以标准方式修剪前导/尾随空格?

If you want it to reject the latter example, you'll have to roll your own function to find/reject multiple spaces.

But my guess is that what you really want to do is strip the extra spaces. See: How do I trim leading/trailing whitespace in a standard way?

西瑶 2024-09-09 17:16:19

仅使用 sscanf() 无法做到这一点,它具有非常基本的功能。如果您确实需要强制执行此操作(是吗?),正则表达式可能更适合这里。

You can't do this using only sscanf(), which has pretty basic functionality. If you really need to enforce this (do you?), regular expressions might be more suitable here.

凡间太子 2024-09-09 17:16:19

它不是最干净的,但这就是我为一个项目所做的。基本上,它不是在格式化字符串中包含一个空格,而是最多占用两个空格(您可以更改它以处理制表符或其他内容)。如果只有一个空格,那么第二个字符仍然为空,如果它不为空,那么它被覆盖。

所以我会将:更改

sscanf(text, "%s %s", name, company);

为:

char space[2] = "\0\0"
sscanf(text, "%s%2[ ]%s", name, space, company);
if(space[1] != '\0') {
    //there was an extra space, handle it however
}

its not the cleanest, but this is how i did it for a project. Basically rather than having a space in the formatted string, it takes up to two spaces(you can change it to also deal with tabs or whatever). If there is only one space then the second char is still null, and if its not null then it was overwritten.

So I would change:

sscanf(text, "%s %s", name, company);

to:

char space[2] = "\0\0"
sscanf(text, "%s%2[ ]%s", name, space, company);
if(space[1] != '\0') {
    //there was an extra space, handle it however
}
傲性难收 2024-09-09 17:16:19

根据sscanf的定义,这是绝对不可能的。为了获得所需的结果,我将手动读取文本变量,搜索两个后续的空白字符。如果找到,则将第二个空白字符替换为 0,然后调用 sscanf。

According to sscanf definition, this is absolutely impossible. To get desired result, I would read the text variable manually, searching for two consequent whitespace characters. If found, replace the second whitespace character with 0 and then call sscanf.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文