#include <stdio.h>char *gets(char *str);

The gets( ) function reads characters from stdin and places them into the character array pointed to by str. Characters are read until a newline or an EOF is received. The newline character is not made part of the string; instead, it is translated into a null to terminate the string.

If successful, gets( ) returns str; a null pointer is returned upon failure. If a read error occurs, the contents of the array pointed to by str are indeterminate. Because a null pointer will be returned either when an error has occurred or when the end of the file is reached, you should use feof( ) or ferror( ) to determine what has actually happened.

There is no way to limit the number of characters that gets( ) will read, which means that the array pointed to by str could be overrun. Thus, this function is inherently dangerous. Its use should be limited to sample programs or utilities for your own use. It should not be used for production code.

Related functions are fputs( ), fgetc( ), fgets( ), and puts( ).

Programming Tip 

When using gets( ), it is possible to overrun the array that is being used to receive the characters entered by the user, because gets( ) provides no bounds checking. One way around this problem is to use fgets( ), specifying stdin for the input stream. Since fgets( ) requires you to specify a maximum length, it is possible to prevent an array overrun. The only trouble is that fgets( ) does not remove the newline character that terminates input and gets( ) does, so you will have to manually remove it, as shown in the following program:

#include <stdio.h> #include <string.h> int main(void) {   char str[10];   int i;   printf("Enter a string: ");   fgets(str, 10, stdin);   /* remove newline, if present */   i = strlen(str)-1;   if(str[i]=='\n') str[i] = '\0';   printf("This is your string: %s", str);   return 0; }

Although using fgets( ) requires a little more work, its advantage over gets( ) is that you can prevent the input array from being overrun.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539 © 2008-2017.
If you may any questions please contact us: