sscanf, scan input from a string

In order to store a particular value to variable from a string, we can use sscanf.

Definition:

int sscanf(const char *str, const char *format, ...);

To store a integer value from a string is easy:

 char text[120]="hello 123 234 223";
 int a[3]={-1,-1,-1};

 sscanf(text,"hello %d %d %d", &a[0], &a[1], &a[2]);
 printf(" %d, %d, %d\n",a[0],a[1],a[2]);

If the format is not match, it will not store the value into the array of integer a[]. Let say if you change your text[120] to this:

 char text[120]="hell 123 234 223";

Your a[] will remain -1, -1, -1.

What if we want to extract string? Using %s is not a good idea. Refers back to the original code,

 char text[120]="hello 123 234 223";
 int a[3]={-1,-1,-1};
 char str[120];

 sscanf(text,"hello %d %d %d",&str, &a[0], &a[1], &a[2]);
 printf("%s %d, %d, %d\n",a[0],a[1],a[2]); 

The lines above is working, str[] contain “hello”, but what if the element is not separate by blank space?

 char text[120]="hello:123:234:223";
 int a[3]={-1,-1,-1};
 char str[120];

 sscanf(text,"%s:%d:%d:%d",&str, &a[0], &a[1], &a[2]);
 printf("%s, %d, %d, %d\n",str,a[0],a[1],a[2]); 

This will fail, str[] now contain “hello:123:234:223″, instead of “hello”. How to solves this?

Change the sscanf line to this:

sscanf(text,"%[a-z-A-Z]:%d:%d:%d",&str, &a[0], &a[1], &a[2]);

Now it works! %[a-z-A-Z] indicate to store all characters from a to z, A to Z. And you can add in any symbol and numbers such as add in 0-9 and underscore.

 %[a-z-A-Z-0-9-_] 

2 thoughts on “sscanf, scan input from a string

  1. a[0] and &a[0] both are not same, former implies the integral element and later implies the address of the integral element a[0] which is required during scanf or sscanf.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>