Search code examples
cloopsif-statementwhile-loopscanf

if statement doesnt work in C despite meeting condition


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main()
{
    int c;
    while(true)
    {
        c = scanf("%d", &c);
        if(c==12)
        {
            printf("goes in");
            break;
        }
    }
    return 0;
}

I am still learning C and I got stuck here. My code is pretty simple but I have no idea why it's not working. The while loop functions normally however I cannot access the if statement despite meeting the condition.

Thank you!


Solution

  • The scanf function returns the number of patterns matched. So if you type a number and press ENTER, that number will first be stored in c by the function, then it will return the value 1 to indicate that 1 value was read. That return value of 1 is then assigned to c, overwriting whatever number you entered.

    Skip the assignment, and c will have the value you entered.

    scanf("%d", &c);
    if(c==12)
    {
        printf("goes in");
        break;
    }
    

    Or better yet, assign the return value to a different variable to see if a number was in fact entered.

    int rval = scanf("%d", &c);
    if(rval == 1 && c==12)
    {
        printf("goes in");
        break;
    }