lundi 25 janvier 2021

If an array is not iterated in an 'else' statement, the statement is triggered spontaneusly [closed]

while (1)
        {
            errno = 0;
            memset(line, '\0', sizeof(line));
            printf("Any more extras: (0 for no more extras)?: ");
            fgets(line, 50, stdin);
            numchoice = (int) strtol(line, &trash, 10);
            if (*trash != '\n' || errno == ERANGE)
            {
                printf("Bad input!\n");
                sleep(3);
            }
            else if (validate(numchoice, "extras") == 0)
            {

                if(ispresent(numchoice, car.extras) == 0)
                {
                    car.extras[i] = numchoice;
                    i++;
                    if(i > 4)
                        break;
                }
                else
                {
                    printf("Duplicate option!");
                    sleep(1);
                    for (int j = 0; j<5; j++)   //if this loop is not included, the program triggers the else statement spontaneously.      
                        printf("\n\n%d\n\n", car.extras[j]);
                }
            }

I initially added the (commented) for-loop for debugging purposes, however noticed the program only runs with it. Without including it, the program triggers the else branch (for duplicate options) peristently after the first iteration of the while loop. Where is the fault here?

Aucun commentaire:

Enregistrer un commentaire