Start New Discussion within our Software Development Community

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.



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

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

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


            printf("Factorial of 0 equals 1.\n");
            printf("Do you want to continue?"); 

                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);   

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!

This article has been dead for over six months. Start a new discussion instead.