我试图用getch()函数制作一个程序,该程序从用户输入密码并将密码存储为用户输入的字符串,但显示内容应包含星号。我被这个弄糊涂了。如果有人能帮忙?

最佳答案

假设您在windows上运行,并且您的编码是ASCII
试试这个:

#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
    char buffer[256] = {0};
    char password[] = "password";
    char c;
    int pos = 0;

    printf("%s", "Enter password: ");
    do {
        c = getch();

        if( isprint(c) )
        {
            buffer[ pos++ ] = c;
            printf("%c", '*');
        }
        else if( c == 8 && pos )
        {
            buffer[ pos-- ] = '\0';
            printf("%s", "\b \b");
        }
    } while( c != 13 );

    if( !strcmp(buffer, password) )
        printf("\n%s\n", "Logged on succesfully!");
    else
        printf("\n%s\n", "Incorrect login!");
    return 0;
}

10-04 21:53
查看更多