开发者

sscanf with multiple spaces?

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.


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?


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.


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜