Home > Mobile >  How to parse floating point number using sscanf
How to parse floating point number using sscanf

Time:05-19

This works well, outputting 1 3

                std::string s("driver at 1 3");
                int c, d;
                sscanf(
                    s.c_str(),
                    "%*s %*s %d %d",
                    &c, &d );
                std::cout << c <<" "<< d <<"\n";

But this fails, outputting 6.95129e-310 6.95129e-310

                std::string s("driver at 1 3");
                double c, d;
                sscanf(
                    s.c_str(),
                    "%*s %*s %f %f",
                    &c, &d );
                std::cout << c <<" "<< d <<"\n";

I tried changing the input to std::string s("driver at 1.0 3.0"); but it fails in exactly the same way

c 17 windows mingw g v11.2

CodePudding user response:

You have a bug in your format string. You should increase the warning your compiler outputs: https://godbolt.org/z/Pfd414o45

#include <string>
#include <cstdio>
#include <iostream>

int main() {
    std::string s("driver at 1 3");
    double c, d;
    sscanf(
        s.c_str(),
        "%*s %*s %f %f",
        &c, &d );
    std::cout << c <<" "<< d <<"\n";
}

<source>: In function 'int main()':
<source>:10:19: warning: format '%f' expects argument of type 'float*', but argument 3 has type 'double*' [-Wformat=]
   10 |         "%*s %*s %f %f",
      |                  ~^
      |                   |
      |                   float*
      |                  %lf
   11 |         &c, &d );
      |         ~~         
      |         |
      |         double*
<source>:10:22: warning: format '%f' expects argument of type 'float*', but argument 4 has type 'double*' [-Wformat=]
   10 |         "%*s %*s %f %f",
      |                     ~^
      |                      |
      |                      float*
      |                     %lf
   11 |         &c, &d );
      |             ~~        
      |             |
      |             double*
Compiler returned: 0

You need to use %lf for double.

  •  Tags:  
  • c
  • Related