sscanf gives wacky numbers

I need to parse a file that has very specific formats for each line, so I thought sscanf would be an easy solution. I tested it out with a single line of the file:

x 0.076 0.724 0.065

So I use the following code snippet to try to extract the values.

1
2
3
4
5
6
char label;
double a;
double b;
double c;
sscanf(line.c_str(), "%c %f %f %f", &label, &a, &b, &c);
cout << label << a << b << c << endl;


It reads the first character x fine, but I'm getting ridiculous values for a b and c:

x -9.25596e+061 -9.25596e+061 -9.25596e+061

Anyone know the cause of this? I've tried changing the format specifiers, but that didn't work.


Last edited on
For double you need to use %lf as format string. This should do.

sscanf(line.c_str(), "%c %lf %lf %lf", &label, &a, &b, &c);
Oh, never seen that format. That seemed to do the trick, thanks!
I'll be honest and say I'm not to familiar with C library input. However, I did do some quick research and I believe the issue is with format specifier. In particular, you are using %f to read to in a variable of type double. This is because of how the input requires a pointer to the variable to read in the input. Not only that, but it also requires the size of the variable to read in this case 8 bytes for the double where as your current format specifier is only telling it to read in the sizeof a float 4 bytes. To fix this change the format specifier of "%f" to "%lf" to read in a double. I hope this helps. Also how come you are using sscanf in C++? You could do the very much the same with stringstream to read in the variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <cstdio>

int main()
{
    std::string line = "x 0.076 0.724 0.065";
    
    // 1. sscanf
    {
        char label;
        double a;
        double b;
        double c;

        int count = std::sscanf(line.c_str(), "%c %lf %lf %lf", &label, &a, &b, &c);
        if (count == 4)
            std::cout << label << ' ' << a << ' ' << b
                      << ' ' << c << std::endl;
    }

    // 2. stringstream
    {
        std::istringstream ss(line);
        char label;
        double a;
        double b;
        double c;
        if (ss >> label >> a >> b >> c)
            std::cout << label << ' ' << a << ' ' << b
                      << ' ' << c << std::endl;
    }

}

Topic archived. No new replies allowed.