c - How to limit the amount of characters entered -
so, i'm working on simple password program. i've got code far
/* simple password prog */ #include<stdio.h> #include<string.h> int main(){ char usrin[9]; char password[]={"axcd8002"}; { fprintf(stdout,"\n password:"); fgets(usrin,9, stdin); if ( strcmp(usrin,password)<0 || strcmp(usrin,password )>0 ) { fprintf(stdout,"\n password incorrect"); }; }while( (strcmp(password,usrin))!=0 ); fprintf(stdout, "\n password correct \n"); return 0; }
this code works correctly, if password incorrect, loop keep going, if it's correct - loop break. doesn't work this: if user enters password @ least 1 character longer, program still correct. instance, if user enters axcd8002aaa, fgets read axcd8002 , , ignore aaa. how can prevent happening?
usrin
has 9 characters, of course characters ignored. give usrin
enough space:
char usrin[100];
and best practice:
fgets(usrin, sizeof(usrin), stdin);
there's problem didn't consider: new line character '\n'
considered valid character fgets
, it's in usrin
, need remove manually before comparing passwords.
Comments
Post a Comment