string to float conversion?

前端 未结 9 1832
-上瘾入骨i
-上瘾入骨i 2020-12-18 14:16

I\'m wondering what sort of algorithm could be used to take something like \"4.72\" into a float data type, equal to

float x = 4.72;
9条回答
  •  自闭症患者
    2020-12-18 14:44

    For C++ This is the algorithm I use:

    bool FromString(const string& str, double& number) {
    
        std::istringstream i(str);
    
        if (!(i >> number)) {
            // Number conversion failed
            return false;
        }
    
        return true;
    }
    

    I used atof() in the past for the conversion, but I found this problematic because if no valid conversion can be made, it will return (0.0). So, you would not know if it failed and returned zero, or if the string actually had "0" in it.

提交回复
热议问题