Thread: sscanf variable format string and number of parameters

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    1

    sscanf variable format string and number of parameters

    Hi,

    I have one text file and need to read parameters stored in each of the files's lines. First, I read the file line by line. All clear, I can use the sscanf without problem for one line but only when all the lines have the same number of parameters. The problem appears when the number of parameters in one line are different. For example:

    PARAM1 PARAM2 PARAM3
    PARAM1 PARAM2
    PARAM1 PARAM2 PARAM3 PARAM4


    The parameters are separated by space.

    I can use the folowing function:

    Code:
    sscanf(line, "%s %s %s", s[1], s[2], s[2]);
    but only for a fixed number of parameters on each line (3 in this example).

    My question is:
    How to use sscanf when the number of parameters in one line is different (3, 2, or 4) like in the PARAMS example above. I refer to sscanf because it's an elegant solution for my need if it can be used like this, but other approaches are welcome too!

    Any help is appreciated!
    Thanks!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Read the line into a buffer using fgets()

    Parse the line one word at a time (strtok, sscanf, strspn, your own loop), and count how many words you find.
    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.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    sscanf could still be used. Just plan for the maximum number of parameters. sscanf returns the number of items retrieved.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. variable number of parameters.. passing between functions
    By dayalsoap in forum C Programming
    Replies: 9
    Last Post: 03-29-2011, 06:06 PM
  2. callee cleanup and variable number of parameters
    By cyberfish in forum Tech Board
    Replies: 14
    Last Post: 07-28-2009, 07:19 PM
  3. function with variable number of parameters
    By mikahell in forum C++ Programming
    Replies: 3
    Last Post: 07-23-2006, 03:35 PM
  4. Replies: 8
    Last Post: 07-27-2004, 02:26 AM
  5. gcc/borland and sscanf format specifiers
    By Sargnagel in forum C Programming
    Replies: 2
    Last Post: 01-24-2003, 06:40 PM

Tags for this Thread