The newline will result in an empty string so the format specifier is not satisfied, so scanf()
does not return. It is somewhat arcane behaviour, but:
int count = scanf( "%16[^ \n]s", name ) ;
will return when newline or leading whitespace is entered with count == 0
. It will also accept no more than 16 characters, preventing a buffer overrun while allowing the > 15 characters test.
To avoid unnecessary tests and multiple calls to strlen()
for the same string:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char name[20] = "" ;
bool name_valid = false ;
while( !name_valid )
{
printf("Please enter a username: ");
int count = scanf("%16[^ \n]", name);
size_t len = count == 0 ? 0 : strlen( name ) ;
name_valid = len > 1 && len < 16 ;
if( !name_valid )
{
int ch ;
do
{
ch = getchar() ;
} while( ch != '\n' && ch != EOF ) ;
printf("invalid input\n");
}
}
printf("> %s\n", name);
return 0;
}
Note that in "invalid input" you need to remove the buffered newline and any preceding junk.