c - How to ensure user-input data is an integer -
i new c, know c#. in c#, use tryparse ensure user typed in correct datatype.
here basic code have c:
int shallowdepth; { printf ("\nenter depth shallow end between 2-5 feet: "); scanf ("%d", &shallowdepth); if (shallowdepth < 2 || shallowdepth > 5) { printf("\nthe depth of shallow end must between 2-5 feet."); } } while (shallowdepth < 2 || shallowdepth > 5);
the problem if type characters, such "asdf", program goes crazy , repeatedly says "enter depth shallow end between 2-5 feet: ". i'm not sure why happening, has because expects int , i'm passing characters.
so how verify user inputted data of int type before trying store in variable? thanks.
this happening because %d
scanf
refuse touch not number , leaves text in buffer. next time around again reach same text , on.
i recommend ditch scanf
, try fgets
, 1 of functions in strtoxxx
family such strtoul
or strtoumax
. these functions have well-defined way of reporting errors , can prompt user more text.
for example do:
char str[length]; long x; if (!fgets(str, sizeof str, stdin)) { /* eof or error. either way, bail. */ } x = strtol(line, null, 10);
at point use number, aware that:
- you can specify pointer
strtol
fill , point first unacceptable character - if result cannot represented
long
strtol
seterrno = erange
. if plan test you must seterrno = 0
beforestrtol
Comments
Post a Comment