std::stod 忽略小数位后的非数值

std::stod ignores nonnumerical values after decimal place

本文关键字:小数 stod std      更新时间:2023-10-16

我正在读取一个带有字符串的值,然后将其转换为双精度值。我希望像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,该函数将为您提供处理的字符数,也许您可以使用这些字符数来满足自己的要求(我不清楚您需要失败的确切内容(。