Node:gets, Next:, Previous:Deprecated string input functions, Up:Deprecated string input functions


If you want to read a string from standard input, you can use the gets function, the name of which stands for "get string". However, this function is deprecated -- that means it is obsolete and it is strongly suggested you do not use it -- because it is dangerous. It is dangerous because it provides no protection against overflowing the string into which it is saving data. Programs that use gets can actually be a security problem on your computer. Since it is sometimes used in older code (which is why the GNU C Library still provides it), we will examine it briefly; nevertheless, you should always use the function getline instead. (See getline.)

The gets function takes one parameter, the string in which to store the data read. It reads characters from standard input up to the next newline character (that is, when the user presses <RETURN>), discards the newline character, and copies the rest into the string passed to it. If there was no error, it returns the same string (as a return value, which may be discarded); otherwise, if there was an error, it returns a null pointer.

Here is a short code example that uses gets:

#include <stdio.h>

int main()
  char my_string[500];
  printf("Type something.\n");
  printf ("You typed: %s\n", my_string);

  return 0;

If you attempt to compile the example above, it will compile and will run properly, but GCC will warn you against the use of a deprecated function, as follows:

/tmp/ccPW3krf.o: In function `main':
/tmp/ccPW3krf.o(.text+0x24): the `gets' function
     is dangerous and should not be used.

Remember! Never use this function in your own code. Always use getline instead.