Saturday, March 12, 2011

%[] explored

%[] consists a set of characters
The left bracket is followed by a set of characters and a right square bracket. The characters between the brackets define a set of characters making up the string. If the first character is not a circumflex (^), the input field consists of all subsequent input characters until the function finds a character not in the character set within the brackets.

void main()
{
char *s;
printf("enter the string:");
scanf("%[0123456789]",s);
printf("%s",s);
}

output:
enter the string:345y678
345

Explanation:
the var s consists 345 because y is not in the character set hence dont take no more characters from y. the above program shows the string can contain only the numbers.....

**********************
If the first character inside the square brackets is a circumflex, the input field consists of all subsequent input characters until the function finds a character that is in the bracketed character set. Thus
lets understand it with the help of an example:
void main()
{
char *s;
printf("enter the string:");
scanf("%[^0123456789]",s);
printf("%s",s);
}

output:
enter the string:sheetal7garg
sheetal

Explanation:
in the above program, string s can't contain any number......... it takes the characters until a number comes.......as in the example input is sheetal7garg and in character set there is [^0123456789] hence take the characters until 7 comes........... hence s contains sheetal.................
**************************************
One more example to understand it......

void main()
{
char *s1,*s2;
printf("enter the string:");
scanf("%5[^abc]%s",s1,s2);
printf("s1=%s\ns2=%s",s1,s2);
}

lets see different outputs....
1.
enter the string:welcome
s1=welco
s2=me

2.
enter the string:india
s1=indi
s2=a

Explanation:
in
scanf("%5[^abc]%s",s1,s2);
%5[^abc] means string s1 can store max 5 characters and does not take a,b or c characters as shown in 1st output s1 consist welco and also the remaining characters i.e. 'm','e' go in s2 string.........................similarly,in 2nd output s1 take characters i,n,d,i and stop when 'a' comes, then 'a' character is in s2 and if there are more characters after 'a' , all these also in s2...........