将字符设为密码,并带有“*”符号并与密码匹配

时间:2015-12-09 17:29:35

标签: c passwords

您好我想创建一个程序,要求我输入两位数的密码。我已经创建了密码,密码应该匹配。如果输入的第一个数字是错误的,那么就会再次询问,如果第一个数字是正确的,那么还剩下一个数字。它应该只运行5次。如果这5次都不正确则结束,当我输入密码时,应该是星号“*”。

    #include <iostream>
    #include <conio.h>


int main(int argc, char** argv) {

    char password=0x00;
    int a=0;
   int b;
    char password2=0x00;
    int c,e;
    do{
        printf("\nEnter a character");

        password=getche();

       if(password=='1'){

        b=(passowrd-48)*10;

        password2=getche();

       if(password=='2'){

       c=password2-48;  

      e= c+b;
       }
}        
        a++;
    }while(e !=12 && a<10); 

        return 0;
    } 

也许有任何提示?

2 个答案:

答案 0 :(得分:1)

此程序应该适用于Windows,但您应该知道getch不是C标准库,也不是POSIX定义的:

#include <stdio.h>
#include <cstdio>
#include <conio.h>


int main (void) {
    char password[20];
    int c,i=0;
    char ch = '*';
    while ((c = getch()) != '\n' && c != EOF){
        password[i] = (char)c;
        i++;
        putchar(ch);
    }

    printf("\nYour Password is %s\n",password);
    return 0;
}

你可以像这样自己编写函数getch

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int getch(void);

int main (void) {
    char password[50];
    int c,i=0;
    char ch = '*';
    while ((c = getch()) != '\n' && c != EOF){
        password[i] = (char)c;
        i++;
        putchar(ch);
    }

    printf("\nYour Password is %s\n",password);
    return 0;
}

int getch (void){
    int ch;
    struct termios oldt, newt;

    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag = newt.c_lflag & ~(ICANON|ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

    return ch;
}

输出:

michi@michi-laptop:~$ ./program 
******
Your Password is passwd

getch函数需要一些修复,但至少你会得到一个想法。

答案 1 :(得分:0)

你想要做的是获取char(密码)但不回应它,并在其中放置一个“*”作为占位符。首先由getch()完成,它不会回应。其次是输入后有putchar("*")

这是可能的实施。

#include <stdio.h> 
int main(int argc, char** argv) 
{ 
    char password; 
    int a = 0;
    // int a=0, b=0, c, e; 
    do { 
        printf("\nEnter a character");
        password=getch();
        putchar("*");
        if(password!='1') { printf("\n\n"); continue; }
        password=getch();
        putchar("*");
        if(password!='2') { printf("\n\n"); continue; }
        // The password is correct, do something here
        a++; 
    } while(a<10); 
    return 0; 
} 

还修复了混乱中的缩进和空白行并删除了无用的变量。除了作为输入的“缓冲区”之外,其他地方都没有使用password,因此可以覆盖它。您已经比较了密码的数字,无需计算十进制数,然后进行比较。