Way to get stringstream >> my_double under g++ to give an infinite value or NaN?
I have a c++ function that takes a string input. In the function, I use stringstream
to extract a double
.
Later, I check to make sure that the double is not NaN or infinity. However, I can't come up with a test input that will make the extraction operator yield either of those values.
Here is the important part of my function. The real use is in some class factory methods.
double from_text(const std::string& word, bool& failed){
double ret; failed = true;
std::istringstream param_in(word);
if(!(param_in >> ret)) {
return ret; }
if(is_nan_or_infinity(ret)) {
//I want to get here
return ret; }
failed = false; return ret;
}
You may say, if you can't produce this, why bother?
I don't want to remove the if because I know that in some implementations, like IBM's, the stream operators can produce such values.
I don't want to ignore the problem because I want to at least 开发者_开发问答get 100% statement coverage in my test cases and making exceptions means I always need to check all those files manually to ensure that the only non-covered lines are my exceptions. Manual inspection means more mistakes. There are only five files using code like from_text right now, so its not impossible, but I'm hoping for a better way.
Edit
To be clear, what I want is a way to get std::istringstream(some_magic_string) >> my_double
to output inf and nan on a test platform consisting of g++ under Ubuntu.
Thus, I want to be able to write:
#include "test_stuff.hpp"
#include "from_text.hpp"
///Maybe more magic goes here
bool failed;
from_text("my_special_nan_producing_input",failed)
test_assert(failed,true,"NAN producing input causes failure");
from_text("my_special_inf_producing_input",failed)
test_assert(failed,true,"Infinity producing input causes failure");
///Clean up from all the special magic
And have from_text execute the branch resulting from ret being NaN or inf.
The way this is handled seems to be implementation dependent. Some will output "inf" or "NaN" on an ostringstream but treat that as an error on the way in. I suggest you do the following:
- Test, via ostringstream, what your implementation puts into a string.
- See if your istringstream returns values or treats them as an error.
- If they are treated as an error, test in your from_text method if you got "inf" or "NaN" and return the appropriate value from there.
Unfortunately, if your software runs on multiple platforms you may need platform specific code to handle each case.
Hope this helps!
精彩评论