0

from the requirements of my final project is to validate the scanned date of birth in the following format (DD-MM-YYYY). the date of birth is a struct formed of 3 integers, day, month and year. So, I scan it from the user as follow:

  scanf("%d-%d-%d",&dob.day,&dob.month,&dob.year);

However, when I enter a character, of course it enters an infinite loop. I tried to use the flushinput concept (as I've used it with other scanned integers). It prevents the infinite loop. However, when re-scanning (through a certain loop), it keeps showing the "INVALID EMAIL" message, even though the entered email is correct! I guess this arises due to the presence of the dashes in the input. So, can anybody tell me what to do?

Here's the part of the code where the issue arises (without the flushinput function):

void dobCheck(DATE dob) ///validates date of birth and rescans it if wrong
{
    while(1)
    {
       if (dob.year<1806 || dob.year>2021 || dob.month<1 || dob.month>12 || dob.day<1 || dob.day >31)
       {
          dobCheckAct(dob); continue;
       }
      if ((dob.year%4)==0 && dob.month ==2 && dob.day >29)
      {
          dobCheckAct(dob); continue;
      }
      if (dob.year%4)!=0 && dob.month ==2 && dob.day >28)
      {
          dobCheckAct(dob); continue;
      }
      if (dob.month == 4 ||dob.month == 6 || dob.month == 9 || dob.month == 11) && dob.day> 30)
      {
          dobCheckAct(dob); continue;
      }
      break;
  }  
}
void dobCheckAct(DATE dob) ///action taken in case of invalid date of birth
{
    printf("\a\n**INVALID DATE OF BIRTH!\n");
    scanf("%d-%d-%d",&dob.day,dob.month,dob.year);
}

Thanks in advance!!

  • If you want to deal gracefully with bad input, you probably don't want to use `scanf`. It's either impossible, or more trouble than it's worth. Checking `scanf`'s return value will help. See also [this question](https://stackoverflow.com/questions/58403537/). – Steve Summit Jan 25 '21 at 14:22
  • 2
    What's the rule? "*You can't use any user-input function correctly unless you* ***check the return***". The approach is to loop continually, prompt, read the input, validate, if good input -- break the read-loop, otherwise, issue an error, and you automatically loop and prompt again. `fgets()` and `sscanf()` provides a far better approach than `scanf()` alone. (don't skimp on buffer size...) – David C. Rankin Jan 25 '21 at 14:23
  • Lengthy example [C For loop skips first iteration and bogus number from loop scanf](https://stackoverflow.com/a/60472657/3422102) – David C. Rankin Jan 25 '21 at 14:27

0 Answers0