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.
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.