user11103264
user11103264

Reputation: 1

Scanf after for loop

I don't understand why if I insert a letter the program executes the printf's after the for loop without letting me insert a value for the scanf after the for loop.

    int main()
    {
    float ascissa, ordinata, d, dis, a[50];
    int i=0, j, count = 0;
    for(;;){
        printf("Inserisci ascissa: (oppure inserisci una lettera per terminare): ");
        if(scanf("%f", &ascissa) != 1)
            break;
        printf("Inserisci ordinata: ");
        scanf("%f", &ordinata);
        punto p1 = creaPunto(ascissa, ordinata);
        printf("Inserisci ascissa: ");
        scanf("%f", &ascissa);
        printf("Inserisci ordinata: ");
        scanf("%f", &ordinata);
        punto p2 = creaPunto(ascissa, ordinata);
        dis = distanza(p1, p2);
        a[i]=dis;
        i++;
    }
    printf("Inserisci d: ");
    scanf("%f", &d);
    for(j=0; j<i; j++)
        if(a[j]<d)
            count++;
    printf("Coppie che hanno distanza minore di d: %d\n", count);
}

Upvotes: 0

Views: 55

Answers (1)

P.P
P.P

Reputation: 121427

Because when you enter a letter to break the for loop, the value entered is remains unconsumed in the stdin buffer. %f doesn't consume the input because of format matching failure.

You need to clear any such unconsumed input yourself. For example, you can have a function to clear:

void clear_stdin(void)
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

and call it:

printf("Inserisci ascissa: (oppure inserisci una lettera per terminare): ");
if(scanf("%f", &ascissa) != 1) {
    clear_stdin();
    break;
}

Similarly, you need to error check & clear all scanf calls.

Related: Why does everyone say not to use scanf? What should I use instead?

Upvotes: 1

Related Questions