converting string to float in c++

前端 未结 3 1229
猫巷女王i
猫巷女王i 2021-01-20 05:22

What is the best way to convert a string to float(in c++), given that the string may be invalid. Here are the type of input

20.1

0.07

x

0

3条回答
  •  鱼传尺愫
    2021-01-20 05:56

    Do neither and use stringstream.

    std::stringstream s(str_val);
    
    float f;
    if (s >> f) {
        // conversion ok
    } else {
        // conversion not ok
    }
    

提交回复
热议问题