I would like to see if a string contains a double as its sole contents. In other words, if it could possibly be the output of the following function:
string
Since no one else has mentioned it: the obvious solution is you want to know whether a string has a given syntax is to use regular expressions. I'm not sure that it's the best solution in this case, since the regular expression for a legal double is fairly complex (and thus easy to get wrong). And your specification is somewhat vague: do you want to accept any string which can be parsed (by >>
for example) as a legal double, or only strings can be returned by your doubleToString
function? If the former, the simplest solution is probably to convert the string to a double, making sure that there is no error and you have consumed all of the characters (Martin's solution, except that it's silly to make it a template until you need to). If the latter, the easiest solution is to reconvert the double you've found back into a string, using your function, and compare the two strings. (Just to make the difference clear: Martin's function will return true
for things like " 1.0"
, "1E2"
, ".00000000001"
and "3.14159265358979323846264338327950288419716939937"
, which your function will never generate.)