Interesting Uses of "scanf"

Adding a space after the format specifier (eg. "%d ")

This has the effect of taking an integer (or float for %f and double for %lf) as input and keep the control untill a non-whitespace character is input. This means that if the input is

123                            d

and the function call for scanf was

scanf("%d ",&n); scanf("%c",&c);

where n and c are int and char respectively, the value saved in n is '123' and in c is 'd' (not a space :-) despite the fact that the inputs were seperated by lots of spaces! This could be generalised for cases with newlines and tabs instead of spaces, where the same behaviour is observed.

Now, what's the use of such a facility? Well, in some situations, you may be asked to take a series of inputs, an int ,and then some chars, which are seperated from the int by a series of spaces or a new line. One thing that can be done is to take the whole input as a line in a char array, and use a loop to locate the chars, or do some checking for a new line. But with this trick at hand, the whole thing becomes quite effortless, and clean!



Posted bysamir at 1:25 AM  

0 comments:

Post a Comment