【发布时间】: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 也会出现同样的行为)在诸如此类的输入上失败?
【问题讨论】:
-
根据your favourite documentation,这是意料之中的。