做了一个控制台方式的程序,需要用户从键盘输入用户名和密码,想实现这样的效果:
User Name: bill
Password: ******“User Name”可以使用下面代码段实现:
char szUserName[256];
printf("User Name:");
gets(szUserName);但是“Password”部分若采用上述方法实现,则无法实现显示"******"的效果,请问这样的效果如何通过标准函数实现呢?(至少要支持backspace编辑)望各位高手不吝赐教,谢谢!

解决方案 »

  1.   

    难道还要自己去控制编辑,例如按backspace去消除前一个密码字符,同时还要更新密码缓冲?
    有没有简单通用一点儿的办法?
      

  2.   

    #include <stdio.h>
    #include <conio.h>
    #include <ctype.h>
    void main( void )
    {
       char buffer[81];
       int i, ch;   printf( "Enter password: " );   /* Read in single line from "stdin" max len is 80: */
       for( i = 0; (i < 80) &&  ((ch = _getch()) != EOF) 
                            && (ch != '\n'); i++ )
         {
          buffer[i] = (char)ch;
          _putch( '*' );
         }   /* Terminate string with null character: */
       buffer[i] = '\0';
       /*if you want display the true chars in test, write to "stdout"*/
       printf( "\n%s\n", buffer );
    }
      

  3.   

    to wangjia184(我就是传说中的SB):还有,怎么去“自己画个*”?printf之后光标就往后移动了,也就是说下次显示位置后移,若按backspace,如何退到前面去显示?莫非要直接操作显存?
      

  4.   

    to wangk(倒之):好像没有处理backspace也?
      

  5.   

    to wangk(倒之):测了一下你给的程序,没有预想中的效果,主要就是没有能够处理特殊按键,如backspace和方向键之类的。
    看起来这个小问题还不算简单也:(
      

  6.   

    用for循环处理非回车键,每次输入一个密码字符并输出一个*
      

  7.   

    #include <iostream>
    #include <string.h>
    #include <conio.h>using namespace std;char* getpass(const char* passwd){
    static char buffer[256];
    int i=0;
    char ch=NULL;
    printf(passwd);
    while(i<127&&ch!='\r'){
        ch=getch();
    if(ch=='\b'){
    if(i>0){
    buffer[--i]=NULL;
    putchar('\b');
    putchar(' ');
    putchar('\b');
    }
    else{
        putchar(7);
    }
    }
    else if(ch!='\r'){
    buffer[i++]=ch;
    putchar('*');
    }}
    buffer[i]=NULL;
    return buffer;}void main(){
        char* passwd;
    passwd=getpass("请输入密码:");
    if(strcmp(passwd,"123"))
    printf("\n password is incorrect\n");
    else 
    printf("\n welcome user!\n");
    return;
    }