I'm writing a program to validate a username that's entered by the user. For the purposes of this project, we're to allow alphabetic letters (upper or lowercase), digits or underscores, but no spaces or other punctuation. It also has to be between 5 and 10 characters total. I believe my issue is with getchar() since I know it can only hold one character at a time, but I'm not entirely sure the best way to fix it. Currently when I run my code it only comes back as invalid. Do I need to change my loop or make adjustments to it? Or is there an issue with my if statement?
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int ch;
int len = 0;
printf("Enter the username: "); //prompt user to enter a username
ch = getchar();
while (ch != '\n') //while loop checking for length of username
{
len++;
ch = getchar();
}
if(isspace(ch) || ispunct(ch) || len > 10 || len < 5){
printf("invalid input.");
}
else{
printf("valid input.");
}
return 0;
}