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

2 comments:

  1. I entered out of boundary values, it means suppose i enter 25/25/2012 , actually it's wrong, but these type of output also it shows like Date : 25
    Month : 25
    Year: 2012

    this not right na,..

    ReplyDelete
    Replies
    1. That you can do by extending above program..once user entered the date then check month is <12, based on month check day is < 31 or 30 or 28. If month is > 12 and Day range is not 1-31 then you can ask the user to re-enter the date. By the way the importance of this post is not to check whether entered date is correct or not but scanning the input using scanf

      Delete