Alberto Rossi
Alberto Rossi

Reputation: 1800

do ... while loop isn't working in main

I wrote a simple program with a function that calculates the area of a circle. The program also asks to the user if he wants to calculate it again and if the input is 'N', the program is supposed to stop.

Here's the narrowed down test case:

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

int main(void)
{
    float r;
    char f;  
    do {    
        printf("Type the radius\n");
        scanf("%f", &r);
        printf("Repeat? [Press N for stop]");
        scanf("%c", &f);
    } while(f != 'N');
    getch();
    return 0;
}

but the loop never stops as it was intended to.

Do you have any suggestion?

Upvotes: 7

Views: 3775

Answers (2)

gifpif
gifpif

Reputation: 4917

replace

scanf("%c", &f);

with

f=getch();

Upvotes: 2

P.P
P.P

Reputation: 121387

scanf("%c", &f);

leaves a newline character in the input stream which is consumed in the next iteration. Add a space in the format string to tell scanf() to ignore whitespaces.

scanf(" %c", &f); // Notice the space in the format string.

Upvotes: 8

Related Questions