gets() — Read a Line

Format

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

Language Level

ANSI

Threadsafe

Yes

Description

The gets() function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to but not including the first new-line character (\n) or EOF. The gets() function then replaces the new-line character, if read, with a null character (\0) before returning the line.

Return Value

If successful, the gets() function returns its argument. A NULL pointer return value indicates an error, or an end-of-file condition with no characters read. Use the ferror() function or the feof() function to determine which of these conditions occurred. If there is an error, the value that is stored in buffer is undefined. If an end-of-file condition occurs, buffer is not changed.

Example

This example gets a line of input from stdin.
#include  <stdio.h>
 
#define MAX_LINE 100
 
int main(void)
{
   char line[MAX_LINE];
   char *result;
 
   printf("Please enter a string:\n");
   if ((result = gets(line)) != NULL)
      printf("The string is: %s\n", line);
   else if (ferror(stdin))
      perror("Error");
}

Related Information