Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than gets(text) or scanf("%s", text) , but not bulletproof. It is meant to be a simple but relatively safe demonstration.

The function mygetline reads user input from the stdin into a string using fgets . Then it attempts to remove a trailing newline that fgets may leave in the string. It returns a pointer to the destination string.

See also Safe Version of gets() and Read a Line of Text from the User, Discard Excess Characters.

#include <stdio.h>
#include <string.h>

char *mygetline(char *line, int size)
{
   if ( fgets(line, size, stdin) )
   {
      char *newline = strchr(line, '\n'); /* check for trailing '\n' */
      if ( newline )
      {
         *newline =  '\0'; /* overwrite the '\n' with a terminating null */
      }
   }
   return line;
}

int main(void)
{
   char text[20] = "";
   fputs("prompt: ", stdout);
   fflush(stdout);
   printf("text = \"%s\"\n", mygetline(text, sizeof text));
   return 0;
}

/* my input/output
prompt: hello world
text = "hello world"
*/
#include <stdio.h>#include <string.h> char *mygetline(char *line, int size){   if ( fgets(line, size, stdin) )   {      char *newline = strchr(line, '\n'); /* check for trailing '\n' */      if ( newline )      {         *newline =  '\0'; /* overwrite the '\n' with a terminating null */      }   }   return line;} int main(void){   char text[20] = "";   fputs("prompt: ", stdout);   fflush(stdout);   printf("text = \"%s\"\n", mygetline(text, sizeof text));   return 0;} /* my input/outputprompt: hello worldtext = "hello world"*/#include <stdio.h>
#include <string.h>

char *mygetline(char *line, int size)
{
   if ( fgets(line, size, stdin) )
   {
      char *newline = strchr(line, '\n'); /* check for trailing '\n' */
      if ( newline )
      {
         *newline =  '\0'; /* overwrite the '\n' with a terminating null */
      }
   }
   return line;
}

int main(void)
{
   char text[20] = "";
   fputs("prompt: ", stdout);
   fflush(stdout);
   printf("text = \"%s\"\n", mygetline(text, sizeof text));
   return 0;
}

/* my input/output
prompt: hello world
text = "hello world"
*/

Edited 6 Years Ago by peter_budo: Adding code tags to old post

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.