My doubt is that, the program works fine if I enter a password that fills the array. However if I enter a password such as \"apple25\", I think it counts the blank spaces in the
Point 1. Always initialize your automatic local variables. Saves you from accidentally accessing un-initialized value.
char arr[10] = {0};
Point 2. Always limit your input length. Saves you from running into undefined behavior by overrunning the allocated memory by longer-than-expected input.
scanf("%9s",arr );
Point 3. Use strlen() to loop over only the valid part of input.
There are several issues here:
arr
.c
when you come across it.I think it counts the blank spaces in the array as charecters and even declares
"apple25"
as a valid password.
Your assumption is almost right. Your program does count characters after the end of user input, but they are not necessarily blanks.
You get this effect with "AAPPLLEE2"
because your code examines ten characters of a nine-character string. The tenth character is null terminator, which is neither a digit nor a letter.
You need to use the actual length for the limit of the loop, rather than hard-coding the limit of ten.
You should also fix the potential buffer overrun:
char arr[11]; // <<== Add one more character for '\0'
printf("Enter a password. \n");
scanf("%10s",arr ); // <<== Tell scanf how big is your buffer
That's because your loop runs over the entire, not just upto the characters you read.
Instead do,
size_t len = strlen(arr);
for (i=0; i<len; i++) {
...
}
You may also want to use fgets() to avoid buffer overrun. If you enter more than 10 characters, you'll overflow arr
, which is undefined behaviour.
Instead of
scanf("%s",arr );
do
fgets(arr, sizeof arr, stdin);
char *p = strchr(arr, '\n');
if(p) *p = 0; //trim the trailing newline, if present