converting string to float in c++

前端 未结 3 1230
猫巷女王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:47

    C++11 actually has functions that do this now, in your case std::stof

    Note that as far as handling your validation, it will throw an std::invalid_argument exception if the argument cannot be converted.

    For completeness, here are more of such functions

    std::stoi    // string to int
    std::stol    // string to long
    std::stoll   // string to long long
    std::stof    // string to float
    std::stod    // string to double
    std::stold   // string to long double
    
    0 讨论(0)
  • 2021-01-20 05:49

    You do it by not ignoring the second parameter - it will tell you where the scanning stopped. If it's the end of the string then there wasn't an error.

    char *ending;
    float converted_value = strtof(str_val.c_str(), &ending);
    if (*ending != 0) // error
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题