在 C++ 中将字符串转换为浮点数
converting string to float in c++
鉴于字符串可能无效,将字符串转换为 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
}
相关文章:
- 将浮点数转换为无符号字符数组并打印出来
- 如何将时间字符串 (M:SS) 转换为浮点数
- 如何将浮点数(*)[6]转换为浮点**类型?
- 如何将浮点数转换为uint8_t?
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- C++ - 转换标准::浮点数组的字符串
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- Zedboard zynq-7000 Opencl 浮点数从类型 'double*' 强制转换为类型 'double' 无效
- 将浮点数转换为字符串时如何加快此代码的速度?
- 我可以安全地将浮点数的结构转换为浮点数组吗C++?
- 如何将带有浮点数的字符串转换为十进制?
- 浮点到整数转换出错(即使浮点数已经是整数)
- C/C++ - 将浮点数转换为字节数组,以便字节保持排序
- 将整数的二进制数据转换为浮点数
- 使用 avr-gcc 隐式转换为浮点数:uint8_t vs. uint16_t
- 将浮点数向量转换为十六进制/二进制字符串
- 精确且无公差地将浮点数转换为字符串