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 set errno = erange. if plan test you must set errno = 0 before strtol

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -