std :: stod忽略小数点后的非数字值 [英] std::stod ignores nonnumerical values after decimal place

查看:132
本文介绍了std :: stod忽略小数点后的非数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取带有字符串的值,然后将其转换为双精度型.我希望像 2.d 这样的输入会因std :: stod而失败,但它会返回 2 .有没有办法确保使用std :: stod在输入字符串中根本没有字符?

I am reading in a value with a string, then converting it to a double. I expect an input such as 2.d to fail with std::stod, but it returns 2. Is there a way to ensure that there is no character in the input string at all with 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会引发异常.

This code should print 0 but it prints 2. If the character is before the decimal place, stod throws an exception.

是否有办法使std :: stod(而且我假设std :: stof也会发生相同的行为)在诸如此类的输入上失败?

Is there a way to make std::stod (and I'm assuming the same behavior also occurs with std::stof) fail on inputs such as these?

推荐答案

您可以将第二个参数传递给 std :: stod 以获取转换后的字符数.这可以用来编写包装器:

You can pass a second argument to std::stod to get the number of characters converted. This can be used to write a wrapper:

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;
}

这篇关于std :: stod忽略小数点后的非数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆