Search code examples
cif-statementscanfdo-while

scanf inside an If statement on a do while loop messes up the inputs


When the input is a negative integer, the program should ask if you want to reset.

It worked fine when I test it with a negative integer. But when I try a positive integer, it doesn't work (I have to enter stuff twice).

int main(void) {
    int user_input;
    char check;

    do
    {
        printf("Enter a positive integer: ");
        scanf("%d", &user_input);

        if (user_input < 0)
            printf("Error. Do you want to continue using the program? y/n: ");
            scanf(" %c", &check);

    } while (check == 'y');

  return 0;
} 

Solution

  • Your second call to scanf should be inside brackets, otherwise it is not part of the if statement. Unlike languages like Python, indendation does not matter.

    Your code always executes scanf(" %c", &check), regardless of the user input.

    int main(void) {
        int user_input;
        char check;
    
        do
        {
            printf("Enter a positive integer: ");
            scanf("%d", &user_input);
    
            if (user_input < 0) {
                printf("Error. Do you want to continue using the program? y/n: ");
                scanf(" %c", &check);
            }
    
        } while (check == 'y');
    
      return 0;
    } 
    

    The following blocks are identical:

    if (something)
        statementA;
        statementB;
    
    if (something)
        statementA;
    statementB;