我必须提示用户输入密码,因此在输入密码时,我希望字符被屏蔽,因此我创建了此代码,其中字符被屏蔽,直到按Enter键为止。但是字符数组pwd无法读取我猜到的字符!

char pwd[10];
while(ch!=13)
{
     pwd[i] = ch;
     ch = '*' ;
     printf("%c",ch);
     ch=getch();
     i++;
}
pwd[i]='\0';
printf("%s",pwd);


当我尝试打印pwd时,什么都没有打印。

最佳答案

作为@Olaf和@EugeneSh。提到过,这是一种可怕的密码输入方式。也就是说,这里有一些帮助。

假设我正在某个地方初始化,请将“ pwd [i] = ch”移至循环的末尾,但应移至“ i ++”之前
整个过程应该看起来像这样(请注意,这仍然是非常错误的):

char pwd[10];
while(ch!=13)
{
     ch = '*' ;
     printf("%c",ch);
     ch=getch();
     pwd[i] = ch;
     i++;
}
pwd[i]='\0';
printf("%s",pwd);


实际上,只有在用户输入字符后,我才可能打印“ *”。让我们解决其他问题。

int i = 0;    /* Since you didn't specify if this was initialized */
char pwd[15]; /* Setting this to 10 would have caused you to overrun your
                buffer.  Not only is that crashy, it's a also a HUGE
                source of security holes.  Let's not do that. */
/* Unless you're waiting for a user to enter in a
   character which happens to be ASCII 13, you'll
   never get out.  Let's just change that to i since
   I'm guessing you want a 13 character password. */
while(i != 13)
{
     char ch=getch();
     pwd[i++] = ch; /* You can post increment right here so you don't
                     have to do it at the end of the loop where you
                     might forget */
     printf("*");
     fflush(stdout);  /* Since we are using printf to a stdout (not
                         stderr, we need to manually flush stdout or
                         things won't show up until a newline is
                         eventually printed. */
}
printf("\n"); /* Print a newline so we don't end up printing the
                 password on the same line */

pwd[14]='\0';
printf("Password entered into our crappy security system: %s",pwd);

关于c - 扫描时遮盖文字-C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30247050/

10-11 22:11