2010/04/10

sscanf - parse pre-defined format string

Parse a string with pre-defined format into lots of different variables. The last string shall be able to contain new line character for other purpose.  :)

#include <stdio.h>

int main(int argc, char **argv)
{
   const char *str="123 456 1234567890 1333555777 Line#1 Hello World !\nLine#2 sscanf parse*0 test\nLine#3 End.\n";
   int       a, b;
   long long c, d;   
   char      e[256];

   /// sscanf(str, "%d %d %lld %lld %s", &a, &b, &c, &d, e);
   sscanf(str, "%d %d %lld %lld %[^\001]", &a, &b, &c, &d, e);
   /// \000 is not able to be used because it's null char, end of string
   /// so we use \001 instead
   /// warning: no closing ’]’ for ’%[’ format
   printf("int       a=[%10d], b=[%10d]\n", a, b);
   printf("long long c=[%lld], d=[%lld]\n", c, d);
   printf("\n%s", e);
}


And the result with %s, marked by ///
yenping@Q8400:~/workspace/scanf$ ./a.out 
int       a=[       123], b=[       456]
long long c=[1234567890], d=[1333555777]

Line#1yenping@Q8400:~/workspace/scanf$

Final version, I got what we want.
yenping@Q8400:~/workspace/scanf$ ./a.out 
int       a=[       123], b=[       456]
long long c=[1234567890], d=[1333555777]

Line#1 Hello World !
Line#2 sscanf parse test
Line#3 End.
yenping@Q8400:~/workspace/scanf$

沒有留言: