Thread: Nested Structure help ~

  1. #31
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    It's a lot easier just to use fgets() for ALL input, then use sscanf() to get what you need.

    By the time you've added full error(*) checking to the code, starting with fgets() offers a fairly simple solution. Patching up scanf() when it's going wrong is messy.

    Eg.
    Code:
    char buff[BUFSIZ];
    if ( fgets( buff, BUFSIZ, stdin ) != NULL ) {
      if ( sscanf( buff, "%d %d %d", 
                &IBcourse.commencingdate.month, 
                &IBcourse.commencingdate.day, 
                &IBcourse.commencingdate.year) == 3 ) {
        // now check for valid dates, such as not allowing Feb 29 on non-leap years
      } else {
        // not 3 integers
        // the side-effect of using fgets() with a large buffer is that it will already have
        // read up to the newline, so there isn't a need to "flush" the input stream.
      }
    } else {
      // EOF or some other I/O error
    }
    You see, making it bomb-proof takes quite a lot of effort.



    (*)For extra security, you shouldn't use sscanf() at all.
    None of the numeric conversions (%d,%f etc) detect overflow or underflow.
    The string conversions %s and %[ are tricky to use correctly when trying to extract a small string from a large buffer.
    %c is just plain pointless, you may as well just use an array index directly into the buffer.
    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.

  2. #32
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    The thing to do is to write your own GetStrings() (or whatever) function... include the appropriate fixups and checks, then call it when you need to read in string data.

  3. #33
    Registered User
    Join Date
    Oct 2011
    Posts
    31
    Ok ~ Thanks everyone. I will keep in mind ^^

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing and using a Array nested Structure
    By Jaxtomtom89 in forum C Programming
    Replies: 2
    Last Post: 11-30-2010, 02:50 AM
  2. pointer to nested structure
    By wahid in forum C Programming
    Replies: 2
    Last Post: 11-10-2010, 04:05 AM
  3. Displaying Data from a Nested Structure
    By shazg2000 in forum C++ Programming
    Replies: 1
    Last Post: 01-09-2005, 10:16 AM
  4. initializing nested structure arrays
    By linucksrox in forum C Programming
    Replies: 2
    Last Post: 06-10-2004, 10:58 PM
  5. nested structure help
    By whistler in forum C Programming
    Replies: 1
    Last Post: 05-17-2002, 10:48 AM