How can I check if a string can be converted to a float?

前端 未结 7 1542
别那么骄傲
别那么骄傲 2021-01-15 04:38

First my context is that of a compiler writer who needs to convert floating point literals (strings) into float/double values. I haven\'t done any floating point programming

7条回答
  •  难免孤独
    2021-01-15 04:57

    I was going to say, simply use the code you already have, but assign the result of strod() to a float instead of a double. But your code is wrong in several ways.

    Firstly, you cannot test errno unless an error has ocurred. Secondly, strtod() will not set errno except for things like range errors. If you pass it an invalid number, like "XYZ", it will not be set.

    More correct use of strtod is:

    char *p;
    double d = strtod( "123.4xyz", & p );
    if ( * p != 0 ) {
       // not a number - in this case will point at 'x'
    }
    

    Using strtod() to read a float, you may lose some precision, but that's the price you pay for using floats - in general, unless you have a very good reason not to, you should always prefer the use of double to float.

提交回复
热议问题