2

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 3
    The compiler should always ignore `gets`, on principle. Don't use it, it's unsafe. – Kninnug Dec 07 '13 at 20:40
  • 3
    Your compiler is right. Ignore `gets()`. Just use `fgets()`. :P –  Dec 07 '13 at 20:40
  • 1
    That's because `scanf()` "slurped" the digits you meant to read, which means that when it's `gets()`'s turn to read, nothing's left. A side note: `gets()` is _extremely_ poor style. Prefer `fgets()` in the future. `gets()` is so unsafe that it was removed in the latest C standard. – Iwillnotexist Idonotexist Dec 07 '13 at 20:40

1 Answers1

5

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • I am a beginnner, I read in the forums today that gets is dangerous, but I still used it because I don`t know the prototype of fgets. – user3078259 Dec 07 '13 at 20:51
  • 1
    Just type 'fgets' in your favorite search engine, you'll get lots of info, including official standards (http://pubs.opengroup.org/onlinepubs/009695399/functions/fgets.html) and lots of examples. – Mat Dec 07 '13 at 20:52