std::stod 忽略小数位后的非数值
std::stod ignores nonnumerical values after decimal place
我正在读取一个带有字符串的值,然后将其转换为双精度值。我希望像2.d
这样的输入会因 std::stod 而失败,但它返回2
.有没有办法确保输入字符串中根本没有 std::stod 的字符?
示例代码:
string exampleS = "2.d"
double exampleD = 0;
try {
exampleD = stod(exampleS); // this should fail
} catch (exception &e) {
// failure condition
}
cerr << exampleD << endl;
此代码应打印0
但打印2
。如果字符在小数位之前,stod 将引发异常。
有没有办法使 std::stod(我假设 std::stof 也会发生相同的行为(在这样的输入上失败?
您可以将第二个参数传递给std::stod
以获取转换的字符数。这可用于编写包装器:
double strict_stod(const std::string& s) {
std::size_t pos;
const auto result = std::stod(s, &pos);
if (pos != s.size()) throw std::invalid_argument("trailing characters blah blah");
return result;
}
此代码应打印 0,但打印 2。
不,这不是指定std::stod
的方式。该函数将丢弃空格(您没有空格(,然后解析您的2.
子字符串(这是一个有效的十进制浮点表达式(,最后在d
字符处停止。
如果您将非nullptr
传递给第二个参数pos
,该函数将为您提供处理的字符数,也许您可以使用这些字符数来满足自己的要求(我不清楚您需要失败的确切内容(。
相关文章:
- C++将浮点指针值舍入为小数位数
- 从给定的 I 和 D 序列中形成最小数
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- stod转换一些sig无花果剪掉
- 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- 计算 PI 最多 42 位小数
- 为什么我必须添加一个小数才能在C++中正确计算此数学
- 返回浮点数的小数位数
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 在数学上将浮点数四舍五入到 N 位小数
- 打印双精度的整个非小数部分
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中对OpenCV垫的小数进行四舍五入?
- 将 int 数组转换为带有小数C++的双精度数组
- 使用 stod() 转换小数点后字母的字符串时没有例外
- Arduino如何制作返回固定大小数组的函数
- 从浮点数中删除小数部分但保留类型的有效方法
- 分配新的零大小数组可以具有有效价值吗?
- c++只关心2位小数,没有设置精度