I have a weird Buffer Clearing Error in this code. This is the line that is causing the error.

if(a<=0)

After you compile the code and run the code put in a group of letters like abc when the programs asks you to put in an integer. The first one or two times you run the code it produces some random massive number. After you run the code one or two times the code magically fixes itself. The code is supposed to ask you to enter another integer if you give a number less than 1 or any letters. The reason I know that line is causing the problem is, if I change the line above to this below then the program runs fine.

while(a<=0)

I'm using a unix system. Can anyone explain why this is happening and how the code magically fixes itself.

#include <stdio.h>
int gcd(int x, int y)
{
    if ( y == 0 )
    {    
        return x;
    }
    else if (x%y == 0)
    {
        return y;
    }
    else
    {
        return gcd(y,x%y);
    }
}

int get_input()
{
    int a, i=0;
    scanf("%d", &a);
    while(getchar() != '\n');
    if(a<=0) 
    { 
        for (i = 0; a <= 0; i++)
        {
            printf("Please enter an integer greater than 0\n");
            scanf("%d", &a);
            while(getchar() != '\n');
        }
    }
    return a;
}

int main()
{
    int x = -1;
    int y = -1;
    int z;
    printf("This program computes the greatest common divisor\n");
    printf("of positive integers x and y, entered by the user\n");
    printf("Inputs must be integers greater than zero\n\n");

    printf("Please enter a value for x:\n");
    x = get_input();
    printf("x: %d\n", x);
    
	printf("Please enter a value for y:\n");
    y = get_input();
    printf("y: %d\n", y);
    
	z = gcd(x , y);
    printf("The GCD of %d and %d is %d\n", x, y, z);
    
	return 0;
}

Check out this link for more information... The problem being discussed here is pretty similar to yours

http://www.daniweb.com/forums/thread259931.html

Thats my own thread. I wasn't clearing my buffer with this below, and now I am.

while(getchar() != '\n');
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.