0

I'm a C beginner and am working on a program that registers flights using structs. Each flight has a code that must follow a certain structure: FLI-XXXX, X being integers. I'd like to use the integers part of the code later on, so I thought the best way to scan for it was using both fgets and scanf. After validating the code using auxiliary variables, I would later write it to the flights struct. However, I'm stuck at the validating part.

The problem is, whenever I call the function that validates a code (opt1) inside an if statement, it runs twice and only works as intended the second time around. Here's my code:

#include <stdio.h>
#include <string.h>

typedef struct 
{
    int num;
    char code[5];
}fl;

fl flight[9999];

int Valid(char a[], int b)
{
    if((strlen(a) != 4) || (b<0 || b>9999)){
        return 0;
    }
    else if(a[0] !='F' || a[1] !='L' || a[2] !='I' || a[3] != '-'){
        return 0; 
    }
    return 1;
}

void opt1(fl a[]){

    char tempCode[5];
    int tempNum;
    
    do
    {
    puts("Insert code:");
    fgets(tempCode, 5, stdin);
    scanf("%d", &tempNum);
    puts("");

    if (Valid(tempCode, tempNum))
    {
        printf("Flight %s%d registered. \n", tempCode, tempNum);
    }
    else
    {
        puts("Flight # invalid.");
    }
    } while (Valid(tempCode, tempNum)==0);

}

int main() {
int opt;

//calling opt1 works as intended
opt1(flight);

//calling inside if statement runs opt1() twice, only the second time as intended
scanf("%d", &opt);

if(opt==1){
    opt1(flight);
}

return 0;
}

And here's an input:

FLI-1234
1
FLI-1234

That returns:

Flight FLI-1234 registered. 
Insert code:
Flight # invalid.
Insert code:
Flight FLI-1234 registered.

I'm not sure why this is happening. Can anyone guide me in the right direction, please? Thank you.

Velgi
  • 1
  • 3
    *Don't* mix `fgets()` and `scanf()` because they have different behaviour with line endings. Instead of `scanf()` you can use `fgets()` and then apply `sscanf()` to the string. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) and [fgets() doesn't work after scanf](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf). – Weather Vane Sep 26 '21 at 19:31
  • 2
    Moreover you say you want to validate the input, yet you have ignored the return value from `scanf`, but that's an essential check towards validating the input. – Weather Vane Sep 26 '21 at 19:37
  • 1
    `fgets(tempCode, 5, stdin);` too small to read in `"FLI=\n"`. – chux - Reinstate Monica Sep 26 '21 at 21:31
  • `valid` returns 0 when you seem to want the input to be valid. Change the return values. – William Pursell Sep 27 '21 at 02:25

0 Answers0