std::stod ignores nonnumerical values after decimal place

谁说我不能喝 提交于 2021-02-05 09:29:41

问题


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?

Example code:

string exampleS = "2.d"
double exampleD = 0;
try {
  exampleD = stod(exampleS); // this should fail
} catch (exception &e) {
  // failure condition
}
cerr << exampleD << endl;

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

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?


回答1:


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



回答2:


This code should print 0 but it prints 2.

No, that is not how std::stod is specified. The function will discard whitespace (which you don't have), then parse your 2. substring (which is a valid decimal floating-point expression) and finally stop at the d character.

If you pass a non-nullptr to the second argument pos, the function will give you the number of characters processed, which maybe you can use to fulfill your requirement (it is not clear to me exactly what you need to fail on).



来源:https://stackoverflow.com/questions/57862338/stdstod-ignores-nonnumerical-values-after-decimal-place

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!