如何循环使用sscanf的? [英] How to use sscanf in loops?

查看:135
本文介绍了如何循环使用sscanf的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个很好地遍历一个字符串的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的,但它会很高兴能够写出类似于你可以从标准输入做些什么事

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 转换符href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/sscanf.html\"><$c$c>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", n, sum, offset);
    }

    printf("sum = %d\n", sum);
    return 0;
}

改变'线'到'数据',因为你不能增加一个数组的名字。

Changed 'line' to 'data' because you can't increment the name of an array.

这篇关于如何循环使用sscanf的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆