C++ 中密码输入

#include 
#include 

#ifdef __MINGW32__
#include 
#endif

#define MAX 100
#define BACKSPACE 8

void system_pause(void);

int main(void)
{
    char passwords[MAX+1], ch;
    int i=0;
    printf("Input the passwords:\n");
#ifdef __MINGW32__
    while((ch = getch()) != '\r' && i < MAX)
#else
    system("stty -echo");
    while((ch = getchar()) != '\n' && i < MAX)
#endif
    {
#ifndef __MINGW32__
        system("stty echo");
#endif
        if (ch == BACKSPACE)
        {
            if (i > 0)
            {
                passwords[--i] = '\0';
                printf("\b ");
                printf("%c%c%c", BACKSPACE, ' ', BACKSPACE);
                fflush(stdout);
            }
            else
                printf("\a"); //bell
                fflush(stdout);
        }
        else
        {
            passwords[i++] = ch;
            printf("*");
            fflush(stdout);
        }
#ifndef __MINGW32__
        system("stty -echo");
#endif
    }
#ifndef __MINGW32__
    system("stty echo");
#endif
    passwords[i] = '\0';
    printf("\nYour passwords is: ");
    printf("%s\n", passwords);

    system_pause();
    return 0;
}

#ifdef __MINGW32__
void system_pause(void)
{
    system("pause");
}
#else
void system_pause(void)
{
    puts("Press any key to continue...");
    system("stty raw");
    getchar();
    system("stty cooked");
}
#endif

关于Zeno Chen

本人涉及的领域较多,杂而不精 程序设计语言: Perl, Java, PHP, Python; 数据库系统: MySQL,Oracle; 偶尔做做电路板的开发,主攻STM32单片机
此条目发表在C/C++分类目录。将固定链接加入收藏夹。