Wednesday 16 November 2011

How do I prevent the user from typing too many characters in a field ? in C programming

How do I prevent the user from typing too many characters in a field?

There are two reasons to prevent a user from typing too many characters in a field. The first reason is that you might want to deal with only a fixed number of characters in your code. The second, and perhaps more important, reason is that if the user types more characters than your buffer can handle, it will overflow your buffer and corrupt memory. This potential danger is often overlooked in C tutoring books. For example,
the following code is very dangerous if the user types more than 50 characters:

char buf[ 50 ];
scanf( “ %s” , buf );

The way to fix the problem is by specifying in your scanning statement the maximum size of the string you want to scan. This task is accomplished by inserting a number between the % and the s, like so:
“ %50s”
This specification will accept, at most, 50 characters from the user. Any extra characters the user types will remain in the input buffer and can be retrieved by another scanning command. It is important to note that a string also needs a null terminator. Therefore, if you want to accept 50 characters rom the user, your string must be of length 51. This is 50 characters for the real string data, plus a byte for
the null terminator.
The following example program tests this technique:
#include <stdio.h>
/*
Program to show how to stop the 
user from typing too many characters in
a field.
*/
int main()
{
char str[ 50 ]; /* This is larger than you really need */
/*
Now, accept only TEN characters from the user. You can test this by typing more than ten characters here and seeing
what is printed.
*/
scanf( “ %10s” , str );
/*
Print the string, verifying that it is, at most, ten characters.
*/
printf( “The output is : %s.\n” , str );
return( 0 );
}

And here’s a sample run of the program. With the input 

supercalifragilisticexpialidocious

the output is

supercalif.

Cross Reference:

None.

No comments:

Post a Comment