Thread: Restrict scanf() input?

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    16

    Restrict scanf() input?

    While reading a %d integer value into scanf, is there a way to restrict or check input so that invalid input like characters won't mess up the program?

  2. #2
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    check its return value

  3. #3
    ---
    Join Date
    May 2004
    Posts
    1,379
    Code:
    if(scanf("%d",&var) != 2)
    {
       ... //var is not 2
    }
    I think that is right

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by sand_man
    Code:
    if(scanf("%d",&var) != 2)
    {
       ... //var is not 2
    }
    I think that is right
    Close. From the man page:
    RETURN VALUES

    These functions return the number of input items assigned,
    which can be fewer than provided for, or even zero, in the
    event of a matching failure. Zero indicates that, while
    there was input available, no conversions were assigned;
    typically this is due to an invalid input character, such
    as an alphabetic character for a `%d' conversion. The
    value EOF is returned if an input failure occurs before
    any conversion such as an end-of-file occurs. If an error
    or end-of-file occurs after conversion has begun, the num-
    ber of conversions which were successfully completed is
    returned.
    In the above case, if the return value was 1, it would mean that you sucessfully scanned in one item, which would be what you want for the above code.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Of course, you then realise that if the user messed it up, scanf() leaves a pile of trash on the input stream which you still have to get rid of, and then you realise that fgets() and sscanf() would have been a better approach.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some help with C program writing
    By The_PC_Gamer in forum C Programming
    Replies: 9
    Last Post: 02-12-2008, 09:12 PM
  2. input from scanf into structure, how?
    By Elite in forum C Programming
    Replies: 8
    Last Post: 03-04-2005, 02:59 PM
  3. restrict input
    By barneygumble742 in forum C Programming
    Replies: 2
    Last Post: 09-09-2004, 05:10 PM
  4. help with input and scanf
    By kpw in forum C Programming
    Replies: 9
    Last Post: 08-28-2001, 08:21 PM