Wednesday 16 November 2011

Why shouldn’t scanf be used to accept data? in C programming

Why shouldn’t scanf be used to accept data?

Although scanf is generally the most-used function for keyboard input, there are times when it is best not to use scanf. These situations can be broken down into various cases: Cases in which the user’s keystrokes must be processed immediately when entered. If you are writing a program in which keystrokes must be acted on immediately after the key is pressed, scanf is useless. scanf waits at least until Enter is pressed. You don’t know whether the user will press Enter one second, one minute, or one century after the key is pressed.
Although this use is obviously bad in a real-time program, such as a computer game, it can also be bad
in common utility programs. If you have a lettered menu, the user will probably prefer to press the
letter a by itself, rather than pressing a followed by the Enter key.
Unfortunately, the standard C library has no functions designed to carry out this action. You must
rely on supplementary libraries or special functions included with your compiler.

Cases in which you need things that scanf might parse away.

scanf is a very smart function—in some cases, too smart. It will cross lines, throw away bad data, and
ignore white space to attempt to satisfy the programmer’s request for input data.

Sometimes, however, you do not need this degree of cleverness! Sometimes you want to see the input
exactly as the user typed it, even if there is not enough of it, too much of it, or such. A case of a program that is not suitable for scanf is one that must accept textual commands from the user. You don’t know ahead of time how many words will be in the sentence that the user will type, nor do you have any way of knowing when the user will press Enter if you are using scanf! u Cases in which you do not know ahead of time what data type the user will be entering. Sometimes, you are prepared to accept input from the user, but you do not know whether he will be entering a number, a word, or some special character. In these cases, you must get the data from the user in some neutral format, such as a character string, and decide what exactly the input is before continuing.

Additionally, scanf has the problem of preserving bad input in the input buffer. For example, if you are
attempting to read in a number, and the user enters a character string, the code might loop endlessly trying to parse the character string as a number. This point can be demonstrated by the following program:

#include <stdio.h>
main()
{
int i;
while( scanf( “ %d” , &i ) ==0 )
{
printf( “Still looping.\n” );
}
return( 0 );
}

The program works fine if you enter a number as it expects, but if you enter a character string, it loops endlessly.

Cross Reference:

None.


No comments:

Post a Comment