Thread: Custom Made Safe Input Function

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    93

    Custom Made Safe Input Function

    I am trying to make a safe input function, since it's tedious to keep writing a bunch of crap with fgets() every time you want to get some input from the user safely.

    This is what I have written so far, and I know it's far from perfect:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void gstring /*Sexy*/ (char *destination_string)
    
    {
    	char *p;
    
    	if ( (fgets(destination_string, sizeof(destination_string), stdin)) != NULL )
    	{
    		if ( ((p = strrchr(destination_string, '\n')) != NULL) )
    			*p = '\0';
    			
    		else 
    			/*ungetc('x', stdin); One idea, to always make the scanf call have a purpose*/
    			scanf("%*s");
    	}
    
    	else
    		puts("Error encountered reading string.");
    
    	return;
    
    }
    First off, I know that if nothing is left in the input buffer because the destination string and the input received are both the same size, then the scanf function is an error.

    How would I go about checking the input buffer?

    The other solution I have is to make a string in the function, of say BUFSIZ, which should be large enough to accommodate any string input, and then strncpy() the appropriate length to the destination string.

    Another idea I was thinking of, was using ungetc() to force something onto the input buffer, so that the call to scanf to clear the input buffer would always have a purpose.

    If someone could look this over and give any ideas/tips, I'd be thankful.

    Thanks.
    Last edited by Beast(); 08-20-2004 at 12:15 AM. Reason: Code Fookup

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM