Thread: scanf problem

  1. #1
    Registered User
    Join Date
    Sep 2010

    Question scanf problem

    peace upon you all every one :

    Iím having a little problem with the scanf() function

    the following code asks three users about their age using

    and then it matches if user_age >= 18 and user_age <= 100 and scanf() returned something except zero.

    if the user entered a character or any except integer scanf() fails and return zero then the code loop back and try to reread the user age .

    the problem is that scanf() wonít re prompt the user to enter any thing !!

    but just keep returning 0 and the program keep trying to reread the age

    here is the code :
    #include <stdio.h>
    int main()
    	int i = 0;
    	int user_age = 0;
    	int scanf_result = 0;
    	for (i=1 ; i<=5 ; i++)
    		printf("user number %i Enter your Age : ",i);
    		scanf_result = scanf("%i",&user_age);
    		if (user_age >= 18 && user_age <= 100 && scanf_result > 0)
    			//if the user input is >= 18 and <= 100 and scanf() returned non zero (succeeded) then
    			//do some work with the user input
    			printf("your age should be an integer from 18 to 100 try again\n");
    			i = i -1;
    	printf ("\n");
    	return 0;

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    scanf does not remove invalid input. That's your responsibility. Check the FAQ.

  3. #3
    The Dragon Reborn
    Join Date
    Nov 2009
    Dublin, Ireland
    while(getchar()!='\n') ;
    will flush the buffer
    You ended that sentence with a preposition...Bastard!

  4. #4
    Join Date
    Aug 2010
    Ontario Canada
    Test the return value from scanf() ... if you're looking for one variable, anything but a 1 returned is an error... scanf("%d",&x) will return 0 if the user types in a letter instead of a number.

    Functions have return values for a reason.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with RPC and scanf
    By Ricardo_R5 in forum C Programming
    Replies: 11
    Last Post: 01-08-2007, 06:15 PM
  2. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 01:35 PM
  3. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-05-2005, 12:42 AM
  4. problem with looping scanf
    By crag2804 in forum C Programming
    Replies: 6
    Last Post: 09-12-2002, 08:10 PM
  5. scanf problem
    By Flikm in forum C Programming
    Replies: 2
    Last Post: 11-05-2001, 01:48 PM