lundi 9 septembre 2019

std::stod ignores nonnumerical values after decimal place

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?

Aucun commentaire:

Enregistrer un commentaire