如何在循环中使用 sscanf? [英] How to use sscanf in loops?
问题描述
有没有好办法用 sscanf
遍历字符串?
Is there a good way to loop over a string with sscanf
?
假设我有一个看起来像这样的字符串:
Let's say I have a string that looks like this:
char line[] = "100 185 400 11 1000";
我想打印总和.我真正想写的是:
and I'd like to print the sum. What I'd really like to write is this:
int n, sum = 0;
while (1 == sscanf(line, " %d", &n)) {
sum += n;
line += <number of bytes consumed by sscanf>
}
但是没有干净的方法可以从 sscanf
中获取这些信息.如果它返回消耗的字节数,那将很有用.在这种情况下,您可以只使用 strtok
,但是能够编写类似于您可以从 stdin
执行的操作会很好:
but there's no clean way to get that information out of sscanf
. If it returned the number of bytes consumed, that'd be useful. In cases like this, one can just use strtok
, but it'd be nice to be able to write something similar to what you can do from stdin
:
int n, sum = 0;
while (1 == scanf(" %d", &n)) {
sum += n;
// stdin is transparently advanced by scanf call
}
有没有我忘记的简单解决方案?
Is there a simple solution I'm forgetting?
推荐答案
查找 %n
转换说明符 sscanf()
和家人.它为您提供所需的信息.
Look up the %n
conversion specifier for sscanf()
and family. It gives you the information you need.
#include <stdio.h>
int main(void)
{
char line[] = "100 185 400 11 1000";
char *data = line;
int offset;
int n;
int sum = 0;
while (sscanf(data, " %d%n", &n, &offset) == 1)
{
sum += n;
data += offset;
printf("read: %5d; sum = %5d; offset = %5d
", n, sum, offset);
}
printf("sum = %d
", sum);
return 0;
}
将line"更改为data",因为您无法增加数组的名称.
Changed 'line' to 'data' because you can't increment the name of an array.
这篇关于如何在循环中使用 sscanf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!