Tuesday, 30 July 2013

Formatting Input-output

Usage of scanf,sscanf

adjusting delimiter, or scanning only specific characers

May be you get a question in your mind. What does ‘[^\n]‘ do ? Does it set the delimiter to ‘\n’. Well, you on the right track. Yes, it does. Instead on ‘\n’, if you had put a ‘\t’ it would consider all words with spaces as stringuntil you press a ‘Tab’. You can even have a  ‘  ‘(a space). The scanf can be expanded as
scanf(” %[^ ]s”,a);  // Note – There is a space after ^
The only differece between scanf(” %s”,a) and scanf(” %[^ ]s”,a) is that, when you enter a string with two words, the former considers each word as a new string whereas the latter consider only the first word as a string and the other word is ignored.
As a Example, consider the string “Hello World“, the former reads “Hello”and “World” as two strings (if you had called ‘scanf’ twice) and the latter reads only the first word “Hello” (even if you had called ‘scanf’ twice) ! Go ahead and experiment with other delimiters !!

Usage of %n in sscanf

It stores the numbers of characters read in a single read. which match the format speciier and stores in speciifed variable.

i.e sscanf(&input[i],"%c:%[^;.]%n",&current,neighbours,&n);

stores read characters in variable n;