Thread: scanf() protection help

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    6

    scanf() protection help

    Hello all.
    I've been trying to implement a protective measure for my scanf() functions in my program.
    Code:
    void add_num(void)
    {
    	int a,b,c;
    	
    	do
    	{
    		printf("Enter an integer to be added to\n");
    	}
    	while (scanf("%d", &a) != 1);
    
    	do
    	{
    	printf("Enter a second integer to be added to the first\n");
    	}
    	while (scanf("%d", &b) != 1);
    	
    	c = (a + b);
    	printf("%d + %d = %d\n", a,b,c);
    }
    The goal is to get the input from the user, and then ask again if scanf doesn't successfully receive input. The problem here is is that when a user give the program bad input, (Like, a character for instance) the while loop just prints the "enter the integer" message on to infinity and doesn't re-evaluate the input.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, you need to clear up whatever is in the input buffer (e.g. a letter). There is a FAQ entry for "How do I clear the input buffer" or something close to that title. FAQ's can be found at the top left of the page.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    You still have a '\n' or some other char in the buffer. You probably want to clear the buffer by reading until you hit a '\n' char before you read from scanf().

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  3. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM