将字符串转换为 C++ 中的浮点数

cod*_*ker 3 c++ string floating-point

鉴于字符串可能无效,将字符串转换为浮点数(在 C++ 中)的最佳方法是什么。这是输入的类型

20.1

0.07

X

0

我使用的strtof效果很好,但问题是它在出错时以及将字符串“0”传递给函数时都返回 0。

我使用的代码非常简单

float converted_value = strtof(str_val.c_str(), NULL);
if (converted_value == 0) {
    return error;
}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以修复此代码,以便区分字符串 0 和错误 0?如果我使用 scanf 有什么缺点?

Mar*_*som 7

您可以通过不忽略第二个参数来做到这一点 - 它会告诉您扫描停止的位置。如果它是字符串的末尾,则没有错误。

char *ending;
float converted_value = strtof(str_val.c_str(), &ending);
if (*ending != 0) // error
Run Code Online (Sandbox Code Playgroud)

  • 这是真正回答问题中所问内容的唯一答案。所有其他人都只是提到“使用这个或那个替代方案”,但实际上并没有解释所要求的内容。 (3认同)

Cor*_*mer 6

C ++ 11现在实际上具有执行此操作的函数,在您的情况下 std::stof

请注意,就处理您的验证而言,std::invalid_argument如果无法转换参数,它将引发异常。

为了完整起见,这里有更多这样的功能

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
Run Code Online (Sandbox Code Playgroud)