将字符串转换为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有什么缺点?
答案 0 :(得分:4)
您可以通过不忽略第二个参数来实现它 - 它会告诉您扫描停止的位置。如果它是字符串的结尾,那么就没有错误。
char *ending;
float converted_value = strtof(str_val.c_str(), &ending);
if (*ending != 0) // error
答案 1 :(得分:4)
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
答案 2 :(得分:0)
不要使用stringstream
。
std::stringstream s(str_val);
float f;
if (s >> f) {
// conversion ok
} else {
// conversion not ok
}