【问题标题】:std::stod ignores nonnumerical values after decimal placestd::stod 忽略小数点后的非数值
【发布时间】:2019-09-09 23:38:15
【问题描述】:

我正在读取带有字符串的值,然后将其转换为双精度值。我希望像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 也会出现同样的行为)在诸如此类的输入上失败?

【问题讨论】:

标签: c++ c++11 std


【解决方案1】:

您可以将第二个参数传递给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;
}

【讨论】:

    【解决方案2】:

    此代码应该打印 0,但它会打印 2。

    不,这不是std::stod 的指定方式。该函数将丢弃空格(您没有空格),然后解析您的 2. 子字符串(这是一个有效的十进制浮点表达式),最后在 d 字符处停止。

    如果您将非nullptr 传递给第二个参数pos,该函数将为您提供处理的字符数,也许您可以使用它来满足您的要求(它是我不清楚你到底需要失败什么)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      相关资源
      最近更新 更多