Tarique wrote:
Quote:
Hello All.
Is the following good enough to be a safe user input routine?
No. Well, it depends on what you think is "good enough,"
but under any definition of "good enough" that's good enough
to be called good, I'd say the answer is No.
Quote:
What else should i do to improve it ?
>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ARRAYSIZE 100
>
/*Clear the input stream before any input */
int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc(f))) && (EOF != ch))
continue;
>
return ch;
}
>
char* get_data( void )
{
static char buffer[ARRAYSIZE];
printf("Enter Data : ");
See Question 12.4 in the comp.lang.c Frequently Asked
Questions (FAQ) list at <http://www.c-faq.com/>.
Quote:
/*flushln(stdin);*/
while( fgets( buffer , sizeof buffer , stdin ) == NULL )
{
It's not at all obvious that "Just keep trying" is a valid
strategy here. fgets() has already informed you that it was
unable to read; why do you think a second attempt will do any
better? Quite plausibly, the program will just spin in this
loop, prompting endlessly and getting nowhere until somebody
loses patience and pulls the plug.
Quote:
puts("Enter a data");
flushln(stdin);
fgets( buffer , sizeof buffer , stdin );
And what happens to the two lines that are consumed here
(one by flushln and one by fgets)? Suppose the user does in
fact "Enter a data" when asked; what happens to that data?
Quote:
}
buffer[ strlen(buffer)-1 ] = '\0';
What happens if the line had more than ARRAYSIZE-1 characters
before the newline? Answer: You (1) don't notice that the whole
line isn't there, and (2) throw away the last of the characters
that you actually managed to read. Problem (2) may also occur on
the last line of a file, if it doesn't end with a newline.
General note: The error-handling is not well thought out.
For example, flushln is careful to check for EOF and to return
EOF if it's detected, but what does get_data do with the alert
that flushln returns to it? Nothing at all! It just ignores
the problem and plows blindly ahead. That's like installing
smoke alarms and taking the batteries out to reduce the noise.
There are many ways to skin the read-a-line cat; some are
found at <http://www.cpax.org.uk/prg/writings/fgetdata.php>.
You needn't necessarily use any of the approaches described
there, but studying them should at least give you ideas about
how you might improve your own.
--
Eric Sosman
esosman@ieee-dot-org.invalid