Use C gets function to read characters from standard input

Syntax

C gets function has the following syntax.

char *gets(char *str);

C gets function is from header file stdio.h.

Description

C gets function reads characters from stdin.

The newline character is translated into a null to terminate the string. It returns a null pointer on failure.

You cannot limit the number of characters that gets() will read.

Example

Read character from standard input by using C gets function.


#include <stdio.h>
#include <stdlib.h>
/*from  w  w  w.ja  va 2s.  c o  m*/
int main(void)
{
  char fname[128];

  printf("Enter filename: ");
  gets(fname);

  printf("%s \n", fname);

  return 0;
}

The code above generates the following result.


Using gets and putchar


#include <stdio.h>
// w ww.j  a  v  a  2s . c o  m
void reverse( const char * const sPtr );
   
int main()
{  
   char sentence[ 80 ];

   printf( "Enter a line of text:\n" );

   gets( sentence ); 

   printf( "\nThe line printed backwards is:\n" );
   reverse( sentence );

   return 0; 

}

void reverse( const char * const sPtr )
{  
   if ( sPtr[ 0 ] == '\0' ) {
      return; 
   }else { 
      reverse( &sPtr[ 1 ] );

      putchar( sPtr[ 0 ] ); 
   }
}

The code above generates the following result.


gets() reads in only text.

It reads everything typed at the keyboard until the Enter key is pressed.


#include <stdio.h>
 //  w  w w  .  j av  a  2  s .c  om
int main(){
    char name[20];
 
    printf("Name:");
    gets(name);
    printf("%s \n",name);
    return(0);
}

The code above generates the following result.

gets(var) is the same as scanf("%s",var).





















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h