0

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"
*/
2
Contributors
1
Reply
2
Views
12 Years
Discussion Span
Last Post by kedhar
0
#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 by peter_budo: Adding code tags to old post

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.