Input a password from the user and check if it has a char, alphabet and digit

前端 未结 4 383
梦谈多话
梦谈多话 2021-01-23 19:48

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

相关标签:
4条回答
  • 2021-01-23 20:03
    • 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.

    0 讨论(0)
  • 2021-01-23 20:07

    There are several issues here:

    • Try entering a password with a size of 10 or longer. You'd overflow arr.
    • You don't stop at the terminating NULL character (value 0). In fact, you count the terminating NULL as "character" and increase c when you come across it.
    • Any garbage afterward is also processed.
    0 讨论(0)
  • 2021-01-23 20:25

    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
    
    0 讨论(0)
  • 2021-01-23 20:30

    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
    
    0 讨论(0)
提交回复
热议问题