In C, how to stop gets() printing a newline form previous input?

1.1k views Asked by At

I'm having problems while using gets in C.

...
int main()
{
    char test[20], m[20];
    int n;

    scanf("%d", &n);

    while(n)
    {   
        gets(test);
        test.kolona = n;

        m = decode(test); //some function

        printf("%s",m.sif);
        putchar('\n');

        scanf("%d", &n);
    }
}

When I enter a number and press enter, it automatically "prints" a newline, before you input the string. I searched a bit and found that this can be avoided if you put a gets before, like this:

...
scanf("%d", &n);
gets(test)

while(n);
{
    gets(test);
    ...
}

But then it messes up again as the loop continues :(

Is there an elegant solution to this?

1

There are 1 answers

1
BLUEPIXY On

sample to fix

int main()
{
    char test[20], m[20];
    int n;

    scanf("%d%*c", &n);//skip the newline following the numeric input

    while(n)
    {   
        scanf("%19[\^n]", test);//gets has been abolished.
        //test.kolona = n;//The array does not have a member field.

        //strcpy(m, decode(test));//m = decode(test); //Can not be assigned to the array in this way 

        printf("%s\n", m);
        //putchar('\n');

        scanf("%d%*c", &n);
    }
}