Main / ProgHintsGeneral Hints for Project ProgrammingThese hints are not project specific. They are generally answers to questions that people ask me. On this page... (hide) 1. A question of converting strings to floatsA student asked: I was looking over the specs. on atoi and found that "If no valid
conversion could be performed, a zero value is returned."
I was wondering if there is anything better that you know of for doing
conversions? Because if a user enters something invalid, then atoi will
return 0, which could be bad (e.g. entering "a" for the radius in part
1, then you'd have a 0 radius and the user would never know they entered
poor input -- though I think atoi converts "a" to it's ASCII value so
maybe that's a bad example).
That's a good question - that I am embarassed to say that I don't have a great answer for.
http://www.codeguru.com/forum/showthread.php?t=231054 discusses many of the alternatives (although, one of them requires code at http://www.elitetrader.com/vb/showthread.php?threadid=62930). Some of the options seem to need lexical casts (which require boost - which is slightly problematic for class), or things using c++ string streams seem to appear on all of the blogs, etc. I don't think (but don't really know) that any of these alternatives deals any more gracefully with the problem you describe. If you give a string that isn't a number, it gets returned as zero. These alternatives seem to focus more on type safety. I offer two suggestions:
Clearly #2 is not as good as #1, but it is sufficient for this class. |