Scanf is perhaps more powerful than most of us think. I am presenting some advanced use of scanf I learnt recently, expecting to be helpful specially to Contest Problem-solvers.

Reading some predefined characters

You can read a string of some predefined characters with scanf. Suppose you want to read a string with only characters B, A, N, G, L, A, D, E, S, H.Do this:

Code:

scanf("%[BANGLADESH]", s);

scanf will stop reading when ever something other than the characters within the square brackets will be read.If the input is "ABDXBSDFS", the scanf will read "ABD".

The %[...] format specifier is called scanset.

Reading a line containing whitespaces

The '^' symbols means NOT inside the square brackets after %. Do this to read a line containing whitespace.

Code:

scanf("%[^\n]", s);

scanf will return only when it reads a newline character.So, say good bye to gets() which produces a warning!

Skipping some characters when reading

Clockhand is an easy problem in UVa online judge. Most bigginers find it dificult because of the input specification. One way to take the input is:

Code:

int h, m;scanf("%d", &h);getchar();scanf("%d", &m);

Read the hour, skipp the colon, read the minute.You can do the whole thing with a single scanf

Code:

scanf("%d:%d", &h, &m);

The first integer will be read, then if found, a colon will be skipped, then another integer will be read.You can skip an unknown data with a %* specifier.

Code:

scanf("%d%*c%d", &h, &m);

This will read two integer and skip a character between them.

Suppose an input specification is:A floting point number in a line, then a character in another line.

And a sample input is

Code:

1.2x

If you do:

Code:

scanf("%lf%c", &d, &ch);

you will read a double and a new line!You can do this insteed to read the correct input:

Code:

scanf("%lf\n%c", &d, &ch);

Recall the way to read a line. With that, the new line at the end of line will not be read. So, you will need to add a '\n'. Like this:

Code:

scanf("%[^\n]\n", s);

The idea of putting the colon was given by Alim (bit0103-Ovid) (without knowing that it realy works!). I used this technique in many of the solutions those had extra characters in input than is needed.