Tuesday, July 2, 2013

Scanf Search Sets in C Programming

         Search sets are sets of characters, which are enclosed in square braces []. These search sets are generally parts of some format specifier. For example, the format specifier %[/-] tells scanf to match any sequence of characters consisting of / and -. All these characters are assigned to the corresponding argument. This argument must be the name of the string. Lets us see how these search sets are used.

// Program Name: Scan_Sets.c

#include <stdio.h>

void main()
{
 
 int date, month, year;
 char separator[2];
 printf("\n Input your date of birth:");
 scanf("%d%[-/]%d%[-/]%d", &date,separator,&month,separator,&year);
 printf("\n Date: %d", date);
 printf("\n Month: %d", month);
 printf("\n Year: %d", year);

}

To Run: gcc Scan_Sets.c
             ./a.out
Input:  Input your date of birth: 12-12/2012
Output: Date: 12
               Month: 12
               Year: 2012

           While scanning the input, scanf will put the hyphen(-) after the date into the separator and after scanning the month, it will place the slash(/) into separator again. Though the program works as expected, we are having the string separator without actually using it for any purpose, other than temporarily storing the separator characters.  

         To avoid this temporary storing we can use assignment suppressing character(*). Using an assignment suppression character tells the scanf that the input field should only be scanned and not assigned to any argument. Let us modify the above program using  assignment suppression character so that we can avoid separator.

// Program Name: Scan_Sets_Sup.c

#include <stdio.h>

void main()
{
 
 int date, month, year;
 char separator[2];
 printf("\n Input your date of birth:");
 scanf("%d%*[-/]%d%*[-/]%d", &date,&month,&year);
 printf("\n Date: %d", date);
 printf("\n Month: %d", month);
 printf("\n Year: %d", year);

}

To Run: gcc Scan_Sets_Sup.c
             ./a.out
Input:  Input your date of birth: 12/12/2012
Output: Date: 12
               Month: 12
               Year: 2012