1

I'm new to c language and trying to write a fail-safe in my program in case of wrong input by the user.

This is the fail-safe part:

int h1, m1;
char junk; /* Storing a colon or a period when people type in the hour */

printf("Enter start hour: ");
while (scanf("%d %c %d", &h1, &junk, &m1) != 3)
{
  printf("Invalid, try again\n");
}

In any case of wrong input (for example entering a char instead of an int) the loop just continues ad infinitum. Doesn't matter if I scan every variable individually, or assign them 0 at the end of the iteration.

I searched Stack for answers, but only found methods for strings (basically moving to 'fgets' or 'isdigit()') or simply for scanning a single integer.

Is there a way to fail-safe the scan both for int and char data types?

sadcat_1
  • 193
  • 10
  • what is for `junk`? hours, minutes and seconds everything is in integer,check the ranges for hours,minutes and seconds if they fall in correct range then only proceed else report error. – csavvy Nov 15 '20 at 17:51
  • Very unclear to me. What's the problem with your current code? – Support Ukraine Nov 15 '20 at 17:54
  • Does this answer your question? [Validating input using scanf's return value isn't working](https://stackoverflow.com/questions/50272231/validating-input-using-scanfs-return-value-isnt-working) – n. m. could be an AI Nov 15 '20 at 18:07
  • There are ways *not* using strings but they are clumsy. If you know what the typical good input will be, input to a string that is twice that length and parse it with `sscanf()` instead of using `scanf()`. If the input is out of spec, just get another one. If the user makes a simple mistake, that will be handled easily. If the user is trying to mess with it, or doesn't understand what to do, there is nothing you can do about it anyway, except to keep on asking for the input. – Weather Vane Nov 15 '20 at 18:07

2 Answers2

0

Put simply, no. scanf is not particularly sophisticated and doesn't handle situations where "the user might input an element, but maybe not" very well.

My suggestion is - read the data using fgets or similar, validate it, then translate it once you're confident it's good.

-1

You can use assert.h library to make sure input is valid, as an example you can assert below code snippet to check if h1 is entered in valid hour range.

assert( h1 <= 24 && h1 >= 0);

edit: (thanks to first two comments.)

You can add do junk = getchar(); while (junk != EOF && junk != '\n'); to clear your input buffer from '\n' that cause that endless behavior.

SOKRATES
  • 16
  • 3
  • It was perhaps downvoted because OP knows how to do the "safe" part, but not how to recover when the input test failed. – Weather Vane Nov 15 '20 at 18:41