C Tutorial/stdio.h/gets
gets
Item Value Header file stdio.h Declaration char *gets(char *str); Function reads characters from stdin. The newline character is translated into a null to terminate the string. Return a null pointer on failure.
You cannot limit the number of characters that gets() will read.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char fname[128];
printf("Enter filename: ");
gets(fname);
printf("%s \n", fname);
return 0;
}
gets() reads in only text
It reads everything typed at the keyboard until the Enter key is pressed.
#include <stdio.h>
int main(){
char name[20];
printf("Name:");
gets(name);
printf("%s \n",name);
return(0);
}
Name:1 1
gets(var) is the same as scanf("%s",var).
Using gets and putchar
#include <stdio.h>
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 ] );
}
}
Enter a line of text: string The line printed backwards is: gnirts