std::string文字列がfloatになり得るかどうかをチェックしつつfloatへの変換を行う場合、通常はstd::stofを用いて
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// Copyright SCIEMENT, Inc. // by Hirofumi Seo, M.D., CEO & President #include <string> #include <iostream> float stofTryCacth(const std::string& a, bool* is_float) { float result = 0.0f; try { result = std::stof(a); } catch (const std::invalid_argument&) { std::cout << "Error: The string '" << a << "' is not float." << std::endl; *is_float = false; return result; } catch (const std::out_of_range&) { std::cout << "Error: The string '" << a << "' is float but out of range." << std::endl; *is_float = false; return result; } *is_float = true; std::cout << "'" << a << "' -> " << result << std::endl; return result; } int main() { float result; bool is_float; result = stofTryCacth("3.14", &is_float); // '3.14' -> 3.14 result = stofTryCacth(" 3.14", &is_float); // ' 3.14' -> 3.14 result = stofTryCacth("3.14 ", &is_float); // '3.14 ' -> 3.14 result = stofTryCacth(" 3.14 ", &is_float); // ' 3.14 ' -> 3.14 result = stofTryCacth("3.14abc", &is_float); // '3.14abc' -> 3.14 result = stofTryCacth("abc3.14", &is_float); // Error: The string 'abc3.14' is not float. result = stofTryCacth("abc", &is_float); // Error: The string 'abc' is not float. result = stofTryCacth("3.14e2", &is_float); // '3.14e2' -> 314 result = stofTryCacth("3.14e-2", &is_float); // '3.14e-2' -> 0.0314 result = stofTryCacth("314.e-2", &is_float); // '314.e-2' -> 3.14 result = stofTryCacth(".314e-2", &is_float); // '.314e-2' -> 0.00314 result = stofTryCacth("3.14e100", &is_float); // Error: The string '3.14e100' is float but out of range. result = stofTryCacth("-3.14e100", &is_float); // Error: The string '-3.14e100' is float but out of range. return 0; } |
のように行うかと …