Read a Line of Text from the User, Discard Excess Characters

Dave Sinkula 0 Tallied Votes 293 Views Share

If the user tries to put 80 characters in a 20-character buffer, you may have issues. This snippet shows one way to cap the input and discard excess input.

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

#include <stdio.h>

char *mygettext(char *text, size_t size)
{
   size_t i = 0;
   for ( ;; )
   {
      int ch = fgetc(stdin);
      if ( ch == '\n' || ch == EOF )
      {
         break;
      }
      if ( i < size - 1 )
      {
         text[i++] = ch;
      }
   }
   text[i] = '\0';
   return text;
}

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

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