this is more like C question, but i failed to google this.
i expect a command parameter in char[], but there may be no argument passed at all, so i need to try to parse this char[] to int and if there is garbage instead of a number, notify user.
i also need to be able to parse negative (with -sign char) numbers from char[].
how can i do this? thanks.
-
Try atmel.com/webdoc/AVRLibcReferenceManual/…Mikael Patel– Mikael Patel2016年07月24日 11:46:08 +00:00Commented Jul 24, 2016 at 11:46
-
Alternatively atmel.com/webdoc/AVRLibcReferenceManual/… that will allow fail\success control.Mikael Patel– Mikael Patel2016年07月24日 11:47:35 +00:00Commented Jul 24, 2016 at 11:47
-
Easiest is maybe atmel.com/webdoc/AVRLibcReferenceManual/… then you can check that 1) a number was parsed, 2) if there are any extra characters, etc.Mikael Patel– Mikael Patel2016年07月24日 11:59:37 +00:00Commented Jul 24, 2016 at 11:59
1 Answer 1
It isn't doable, reliably, with the given specs. If the array has garbage in it, it won't necessarily fail to parse as an int. That said, you can try to parse as an int with atoi() or sscanf(), as suggested in the comments, and report that it did or did not parse, but not necessarily whether it is valid in some respect.
If you're in control of the array, zero its first element. Then if you get back a non-empty string, at least you'll know some command parameter had been placed in it.
-
but sscanf did nice job, returning 0 if it can't fill the int variable, thus telling that there is no valid int argument passed.curly brace– curly brace2016年07月24日 12:02:55 +00:00Commented Jul 24, 2016 at 12:02