Thread: sscanf

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    175

    sscanf

    I have following code snap written in VC++ 6.0
    if ( sscanf( p,"%02x",&ID ) != 1 )
    {
    printf("ID = %d\n",ID);
    return Error;
    }

    If p = “tt” or “TZ” or “Za” or “R5” it returns error but “4T” or “7G” does not.

    What change do I need to make to return error even for “4T” and “7G”?

    That is, I want to return error if any of the character is non-numeric.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Don't use sscanf. You cannot force it to read 2 bytes always. You should just do it manually.

    Read one byte. Check for 0-9 or a-f. If it isn't, throw an error. If it is, read another byte and check it.

    You're misunderstanding how the *scanf functions work. They read until they don't find something that is readable. Then they put that item back onto the stream, so it counts as not being read.

    So, they see that 4 or 7 is valid, so they use it. They see that T or G is invalid, so they say, well, we've found one item. Push the T or G back, and return that we've found one usable item...

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

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    strtol() : You can use this with error checking quite easily.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sscanf and string handling question
    By ursula in forum C Programming
    Replies: 14
    Last Post: 05-30-2009, 02:21 AM
  2. Problem using sscanf fgets and overflow checking
    By jou00jou in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 06:42 AM
  3. Problems reading formatted input with sscanf
    By Nazgulled in forum C Programming
    Replies: 17
    Last Post: 05-10-2006, 12:46 AM
  4. sscanf question
    By Zarkhalar in forum C++ Programming
    Replies: 6
    Last Post: 08-03-2004, 07:52 PM
  5. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 08:46 AM