0

I am trying to use following code to read the second number inside the parenthesis, but it doesn't work, I am following the method in this post How to use sscanf in loops?. I debug my code, the problem is it doesn't enter the while loop, can someone tell me how to fix it?

#include <stdio.h>
#include <string>

int main(void)
{
    std::string line = "(1:1.1) (2:18.5) (3:40.0) (4:11.0)";
    char const *data = line.c_str();
    int offset;
    int index;
    double value;
    double sum = 0;

    while (sscanf(data, " (%d:%lf)%n", &index, &value,&offset) == 1)
    {
        sum += value;
        data += offset;
    }

    printf("sum = %d\n", sum);
}
Community
  • 1
  • 1
ascetic652
  • 472
  • 1
  • 5
  • 18

1 Answers1

1

To print double you should use %lf as same as scan, and instead of checking if sscanf returns 1, you should check for when it returns greater than 0.

int main(void)
{
    std::string line = "(1:1.1) (2:18.5) (3:40.0) (4:11.0)";
    char const *data = line.c_str();
    int offset;
    int index;
    double value;
    double sum = 0;

    while (sscanf(data, " (%d:%lf)%n", &index, &value,&offset) > 0)
    {
        sum += value;
        data += offset;
    }

    printf("sum = %lf\n", sum);
}
cpatricio
  • 457
  • 1
  • 5
  • 11
  • In most cases, it would be better to be specific rather than vague in your expectations. What if sscanf was only able to match the `index`? – smac89 Nov 03 '16 at 04:58