If you want to limit the number of characters the user may type at the console, then you're going to have to use utilities not present in the C language itself. The standard C I/O routines only see an input stream, which isn't updated until after the user types Enter. You might want to look at ncurses, particularly the forms library, for that sort of functionality.
You can limit how much input your program reads from the input stream in a couple of ways. If using fgets
, you pass a separate parameter indicating the size of the input buffer:
char buff[N+1]; // where N is the max number of characters you want to allow
if ( fgets( buff, sizeof buff, stdin ) )
{
// process contents of buff
}
In this code, only sizeof buff - 1
characters are read from the input stream and stored to buff
. However, this has no effect on how many characters the user may type in from the console (since fgets
blocks until the user hits Enter).
If using scanf
, you can use a maximum field width as part of the conversion specifier:
if ( scanf( "%19s", buff ) == 1 )
{
// process buff
}
Unfortunately, there isn't a good way to pass the field width as an argument to scanf
(like you can with printf
); it has to be hardcoded as part of the conversion specifier.