With
scanf()
and strings, you should always pass the width to specify the max. number of chars to be stored (pass one less than the size of the char array to store the terminating
NULL
char). So with max. 20 chars use:
char a[21];
scanf("%20s",a);
To get the number of chars entered, use the
strlen()
function afterwards. To show a warning when too much chars has been entered, allow one more character to be scanned and compare the final string length:
char a[22];
scanf("%21s",a);
if (strlen(a) > 20)
{
}