Thread: sscanf help

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    1

    sscanf help

    Hi
    I am trying to split a string with the form of "name1=value1&name2=value2" into two seperate strings. The first one would be "name1=value" and the second "name2=string2". Basically split it up at the '&" sign. I was successful in getting the first one stored but i'm unable to get it to split at the & sign. Here is a verion of my code:
    Code:
    char *user_name;
    char strname[30], garb[30];
    
    user_name = "username=hello&b1=submit";
    sscanf(user_name, "username=%s", &strname);
    printf("<P> %s", strname);
    
    I also tried other combinations of sscanf:
    sscanf(user_name, "username=%s %s", &strname, &garb);
    sscanf(user_name, "username=%s &%s", &strname, &garb);
    sscanf(user_name, "username=%s &b1%s", &strname, &garb);
    sscanf(user_name, "username=%s" "%s", &strname, &garb);
    sscanf(user_name, "username=%s %s", strname, &garb);
    and none of them worked. Can anyone help me out here?
    Last edited by Salem; 12-08-2006 at 04:00 PM. Reason: Added code tags

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    First off, you don't need the & when referring to arrays in sscanf calls.

    You need to use character classes in your sscanf call
    Code:
    sscanf(user_name, "username=%[^&]&b1=%s", strname, garb);
    The [^&] conversion specifies anything which isn't an &
    Think of %s being like [^ \t\n]
    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
    ex-samurai §áßø†æ™'s Avatar
    Join Date
    Nov 2006
    Location
    England
    Posts
    18
    maybe you can use strtok() and set the delimiter to &

  4. #4
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Strtok would be a good idea cause it alters your string. Before using the strtok u got to get the backup of that string.

    ssharish2005

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