Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

loops

scanf

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?

like image 262
Alberto Rossi Avatar asked May 12 '13 12:05

Alberto Rossi


2 Answers

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.
like image 136
P.P Avatar answered Sep 21 '22 06:09

P.P


replace

scanf("%c", &f);

with

f=getch();
like image 45
gifpif Avatar answered Sep 20 '22 06:09

gifpif