Thread: Another example of sscanf function

  1. #1
    Registered User
    Join Date
    Oct 2011
    Location
    Montreal Canada
    Posts
    6

    Another example of sscanf function

    Please add the following to the sscan discussion example (thread from 2005)

    There are times that we have a line of test as:

    line[]= "xyz= "abc"; or
    line[]=xyz='abc'; or
    line[]= xyz=abc;

    AND we want to select out the left and right of the equal sign into two variables. With the sscanf()
    Code:
     
    char *left;
    char *right;
    //we want *left=xyz; and *right=abc;
    
    Here is an example of sscanf that does just that for right with/out quotes. 
    
     if (   sscanf (line, "%[^=] = "%[^"]"", left, right) == 2
         ||  sscanf (line, "%[^=] = '%[^\']'",   left, right) == 2
         ||  sscanf (line, "%[^=] = %[^;#]",    left, right) == 2) 
    {
          do_your_thing(left,right);
    }
    The sscanf returns an integer, the number of items picked out. We stop after the first successful scan.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Perhaps you can post a link to the thread you are referring to.

  3. #3
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Your example has an unmatched double-quote.
    Your code has unescaped double-quotes in the first sscanf format.
    You haven't defined any space for left and right (they can't just be pointers to nowhere).
    (And you should limit the sscanf string inputs to one-less-than their sizes.)

    The general problem with using sscanf to do this is that you can't ignore escaped quotes within
    the containing quotes. greeting = "hello "there""
    Code:
    #include <stdio.h>
    
    int main() {
      char line[1024], left[256], right[256];
    
      while (fgets(line, sizeof line, stdin) != NULL) {
        if (   sscanf (line, "%255[^=] = \"%255[^\"]\"",  left, right) == 2
            || sscanf (line, "%255[^=] = '%255[^']'",     left, right) == 2
            || sscanf (line, "%255[^=] = %255[^ \t\n;#]", left, right) == 2) 
        {
                printf("[%s] [%s]\n", left, right);
        }
      }
    
      return 0;
    }
    Last edited by algorism; 01-26-2016 at 02:24 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. understanding sscanf() function
    By ak47 in forum C Programming
    Replies: 6
    Last Post: 01-03-2014, 11:50 PM
  2. using %[ ] in sscanf
    By damasgate in forum C Programming
    Replies: 2
    Last Post: 04-05-2010, 07:15 PM
  3. sscanf
    By cheryl_li in forum C Programming
    Replies: 2
    Last Post: 05-02-2003, 07:55 AM
  4. What is wrong with my sscanf function?
    By doampofo in forum C Programming
    Replies: 5
    Last Post: 03-09-2003, 10:42 PM
  5. SSCANF help
    By mattz in forum C Programming
    Replies: 7
    Last Post: 12-10-2001, 04:53 PM

Tags for this Thread