Hello guys,

I am new here. I have been practicing programming in C as I am going back to school. The program below is supposed to be really simple. It would help you calculate the factorial of a number. But I don't know why I can't get the scanf function for the character input to work. Any help will be greatly appreciated.

Thanks,

Michael

#include <stdio.h>
int main (void)
{
    int input, i, output;
    char yes;

    printf("Welcome to the factorial calculator.\n");
    yes='y';
    while(yes=='y')
    {
        printf("Input a non-negative number:");
        scanf("%d", &input);

        while(input<0)
        {
            printf("Input value must be positive.\nInput a non-negative number:");
            scanf("%d", &input);
        }

        if(input==0){


            printf("Factorial of 0 equals 1.\n");
            printf("Do you want to continue?"); 
            scanf("%c",&yes);
        }

            else
            {
                output = 1;
                for(i=1; i<=input; i++)
                    output = output *i;
                printf("Factorial of %d equals %d\n",input, output);
                printf("Do you want to continue?"); scanf("%c",&yes);   
            }
    }
    return(0);
}

After each scanf(), add a getchar() to pull the left-behind newline char, off the keyboard buffer.

Scanf() is fragile - it requires a clean input stream, and even then, it should be used for highly formatted input, only.

fgets() is far more robust and flexible. Please use [code] tags around your program code!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.