gpt4 book ai didi

c - 使用 "*"符号获取字符作为密码并与您的密码匹配

转载 作者:行者123 更新时间:2023-11-30 15:14:05 26 4
gpt4 key购买 nike

您好,我想创建一个程序,要求我输入两位数的密码。我已经创建了密码,并且密码应该匹配。如果输入的第一个数字错误,则立即再询问一次,如果第一个数字正确,则再剩下一个。它应该只运行 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;
}

也许有什么提示?

最佳答案

该程序应该在 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 函数需要一些修复,但至少你得到了一个想法。

关于c - 使用 "*"符号获取字符作为密码并与您的密码匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com