main-proghints

General Hints for Project Programming

These hints are not project specific. They are generally answers to questions that people ask me.

1.@ A question of converting strings to floats

A 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.

atof is archaic thing (dating back to the old C library), but I am not that familiar with the modern alternatives.

http://www.codeguru.com/forum/showthread.php?t=231054» discusses many of the alternatives(although, one of them requires code at «<FLOATING LINK: 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:

  1. check to make sure that the string really contains just numbers (and maybe period, plus, minus. oh and maybe scientific notation format stuff). you might even do this only if atof returns zero
  2. define that non-number values are interpreted as zero (or whatever atoi does)

Clearly #2 is not as good as #1, but it is sufficient for this class.

Page last modified on September 27, 2009, at 07:59 AM