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

converting string to float in c++

本文关键字:转换 浮点数 字符串 C++      更新时间:2023-10-16

鉴于字符串可能无效,将字符串转换为 float(在 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;
}

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

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

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

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

两者都不做,使用 stringstream

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