gets function is not reading my variable

208 Views Asked by At

I noticed today that sometimes when I use the gets function my compiler simply ignores it. OK. This is an example where gets works:

#include <stdio.h>
void main()
{
    char s[50];
    gets(s);
    puts(s);
}

Now if I make this simple change to my program, the function gets is ignored:

#include <stdio.h>
void main()
{
    int n;    
    printf("dati n:\n");    
    scanf("%d",&n);    
    char s[50];
    gets(s);
    puts(s);
}

"ignored" means that when i run the program the compiler reads the variable and then quits without reading my string. Why does that happen? Thank you.

1

There are 1 best solutions below

2
On

Your scanf only consumes the number you typed. Anything else after that including the carriage return/newline you typed, is left in the IO buffers.

So gets picks up whatever was left after the number (which is possibly just a newline character) and returns immediately.

As commenters have noted: don't use gets. It has actually been removed from the C standard (no longer in C11) since it is fundamentally unsafe. Use fgets instead.