Read a Line of Text from the User

Dave Sinkula 0 Tallied Votes 304 Views Share

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"
*/
kedhar 0 Newbie Poster
#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"
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.