sscanf的:获得第一和最后一个令牌在一个字符串 [英] sscanf: get first and last token in a string
问题描述
是否有可能通过使用sscanf会得到的第一个标记,然后跳过一些代币,然后拿到最后一个?
Is it possible by using sscanf to get the first token then skip some tokens and then get the last one?
例如,/ bin中的输出/ PS -fu1000
For example, the output of /bin/ps -fu1000
cm 2249 1548 0 0:00.00 ttys001 0:00.01 man sscanf
我曾尝试:
sscanf(line, "%s %[^\n]", user, cmd);
结果应该是:
user = "cm";
cmd = "man sscanf":
不过,这是行不通的。
But it does not work.
推荐答案
是的,但它的丑陋,不能正确错误检查。
Yes, but it's ugly and can't be error checked properly.
/* assuming `user` and `cmd` are character arrays defined with 42 bytes */
if (sscanf(line, "%41s%*s%*s%*s%*s%*s%*s %41[^\n]", user, cmd) != 2) {
/* handle error */
} else {
/* hopefully ok */
}
您可以取代一些%* S
与%* D
。在 *
表示,该项目被解析,但不指定任何地方(它被忽略)。
You can replace some of the %*s
with %*d
. The *
means that the item is parsed but not assigned anywhere (it is ignored).
在声明中,也有厘米
和人sscanf的
在你的例子。
In the statement, there are 6 ignored items corresponding to the items between "cm"
and "man sscanf"
in your example.
另外请注意我限制了输入41个字符的scanf函数本身。确保你不要在外面对象写。
Also note I limited the input to 41 characters in the scanf itself. Make sure you do not write outside the objects.
编辑:我最后一次转换之前加一个空格,因为不像%S
或%d个
转换, %[
转换不会跳过前导空白。
I added a space before the last conversion because, unlike %s
or %d
conversions, the %[
conversion does not skip leading whitespace.
这篇关于sscanf的:获得第一和最后一个令牌在一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!