Question

I'm writing a code of a program that reads an input choice from the user and depending on that it calculates (area, circumference, volume, or quit)

#include<stdio.h>

int main(void)
{
    double radius=0.0;
    double area=0.0;
    double volume=0.0;
    double height=0.0;
    double circumference=0.0;
    const double pi=13.459820934;

    char choice;

    do
    {
    printf("Choose what you want to do : \n"
           "Calculate Area          A\n"
           "Calculate Circumference C\n"
           "Calculate Volume        V\n"
           "Quit                    Q\n");
    /*scanf("%c",&choice);*/
    choice=getchar();

    printf("please enter radius : ");
    scanf("%lf",&radius);

    if(choice=='V')
    {
        printf("please enter height : ");
        scanf("%lf",&height);
    }

    area = pi * radius * radius;
    volume = height * area;
    circumference = 2 * pi * radius;

    switch (choice)
    {
    case 'A':
        printf("Area = %lf\n\n",area);
        break;
    case 'V':
        printf("Volume = %lf\n\n",volume);
        break;
    case 'C':
        printf("Circumference = %lf\n\n",circumference);
        break;
    default:
        printf("Not a good answer !!\n\n");
    }
    }while(choice!='Q');

return 0;
}

when I run the program it worked well for the first do loop but after pringting the choices again as it begins the loop for the second time, it didn't wait for me to enter my choice, it directly printed "please enter radius"

when I debugged the program, I found there was '\n' in choice when it began the loop for the second time, how can I remove this '\n' every loop? I knew that this '\n' resulted from reading the user choice followed by from the first time the loop ran, but I don't know why the choice is removed from choice while was not?

I've tried to initialize choice before displaying the choices to the user but the same problem happened

any help please? thanks in advance

Was it helpful?

Solution

The \n character is leaved behind by the scanf call after pressing Enter key . You need to consume this \n before next iteration, otherwise this \n character will read by next scanf or getchar.

Use the snippet

int ch;
while((ch = getchar()) != EOF || ch != '\n');

just before the closing brace } of do-while or after the second scanf.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top