This page has been designed specifically for the printed screen. It may look different than the page you were viewing on the web.
Please recycle it when you're done reading.

The URI for this page is { http://cc.byexamples.com }

sscanf, scan input from a string Posted on January 18th

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-_] 
Trackback URL
Leave your own comments about this post: