home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!math.fu-berlin.de!news.netmbx.de!Germany.EU.net!mcsun!sun4nl!and!jos
- From: jos@and.nl (Jos Horsmeier)
- Newsgroups: comp.lang.c
- Subject: Re: How is NaN recognized?
- Message-ID: <3358@dozo.and.nl>
- Date: 30 Aug 92 13:00:02 GMT
- References: <5569@ucsbcsl.ucsb.edu>
- Organization: AND Software BV Rotterdam
- Lines: 48
-
- In article <5569@ucsbcsl.ucsb.edu> 6500mack@ucsbuxa.ucsb.edu (Michael P. Mack) writes:
- |I am using scanf() to read in a float that is entered by the user. If
- |an invalid string is typed such as "-" or "." then the variable is
- |assigned -0.NaN(DFD5480000000000... or -0.NaN(DFD9400000000000000...
- |
- |How do I detect when the float is a NaN so that I can set it to 0.0?
-
- Don't use scanf() for this, use a combination of fgets(), to read a line
- and atof() to convert the input string to a double value. atof() returns
- 0.0 if the string could not be converted to a double value and it
- sets (I'm not sure if all implementations do this) the errno variable
- to ERANGE in case of overflow.
-
- If you realy want to play it on the safe side and control all the
- keystrokes from the user, you can implement a small DFA to scan the
- incoming characters. I think (I didn't test it) the following DFA
- could do the job for you:
-
- + - <d> . e
- +---+---+---+---+---+
- 1 | 2 | 2 | 2 | 3 | |
- +---+---+---+---+---+
- 2 | | | 2 | 3 | 4 |
- +---+---+---+---+---+
- 3 | | | 3 | | 4 |
- +---+---+---+---+---+
- 4 | 5 | 5 | 5 | | |
- +---+---+---+---+---+
- 5 | | | 5 | | |
- +---+---+---+---+---+
-
-
- Note: <d> is any digit. State 1 reads an optional +/- sign or the first
- digit or the decimal point. State 2 reads following digits, the
- decimal point or the exponent sign. State 3 reads the optional
- fraction part and state 4 and 5 read the exponent. All other
- (blank) entries indicate an error if the current keystroke is
- not a new line character, otherwise the input has been scanned
- successfully.
-
- It's not difficult to implement the DFA described above, either in
- tabular form or as one big switch statement.
-
- I hope this helps a bit,
-
- kind regards,
-
- Jos aka jos@and.nl
-