While receiving UART commands, I need to convert strings to numerical values. For example, string "1.23" would produce float number 1.23 using function 'atof()':
Unfortunately, in the case of a typo this function will return a valid number also ("0"), which will be passed to the program. For example:
atof('1.$23…')=0, ($ is a typo)
Is there any built-in function to check for valid input number?
You are seeing an error return value, so test your input for invalid,
This function returns the converted floating point number as a double value. If no valid conversion could be performed, it returns zero (0.0).
I know that atof() returns "0" for NaN. That is a problem, as occasionally I may need to send valid string "0.0" as well, which is valid number. So I can not rely on that criteria. I can custom check input string byte-by-byte, and apply various rules testing for NaN, but maybe there is EXISTING function for that in C. For example, I found C++ equivalent, which will through an exception, but nothing in C so far.
A different function you may use is scanf(), but it will stop at the point where an unexpected character is obtained. Quite more promising would be to check the incoming string for legal characters ('0'..'9','.') and act accordingly to the result.
Seems like people having no shortage of issues with scanf, just google that.
Maybe with atof() simply test the raw data on source end and insert a special char/byte
and act accordingly on receipt end raw data before submitting to conversion.
Not elegant, but then neither is C.
Thank you for feedback. I was looking for such function for some time and was hoping that solution exist. So it is official now. Such function would be useful when firmware settings are manually updated thru UART terminal.
As the other person already stated above, ALWAYS validate and range check your input. Never trust your input. scanf() sucks at processing user-typed input, since its very possible that you'll get illegal characters at some point.
1) remove leading and trailing white-space, which includes CR and LF.
2) validate each char in the incoming string against: plus, minus, period, numerics.
To check that input string represents a numeric, use a solution:
Works fine. It obviously doesn't checks the bounds, and string has to be trimmed.
Welcome in the forum!
That depends on what you expect. You can convert a single byte into two hexadecimal digits or into three decimal digits. There is a sprintf() function or an itoa() macro for conversions.
As long as its 0-terminated, use a simple type-cast of the pointer. Of, and please open a new thread when asking a new question. Thanks!