Reputation: 123
Hello I want to create a program that asks me for a two digit password. I have created the password and the password should match. If the first digit entered is wrong then immidiatly asks one more time , if the first digit is right then is one more left. It should runs just 5 times. If none of this 5 times is right it ends and when I type the password should be as star sign "*".
#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;
}
Maybe any hint?
Upvotes: 0
Views: 669
Reputation: 585
What you want to do is get the char (password) but not echoing it, and put a "*" there as a place holder. First is done by getch()
, which will not echo. Second is by having a putchar("*")
following the input.
Here's the possible implementation.
#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;
}
Also fixed the indents and blank lines in chaos and removed useless variables. password
isn't used elsewhere except as a "buffer" for input, so it's OK to override it. You have already compared digit by digit of the password, no need to calculate what it is in decimal and then compare it.
Upvotes: 0
Reputation: 5307
This program should work on Windows but you should know that getch
isn't a C
standard library, nor is it defined by 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;
}
Any way you could write the function getch
yourself like this:
#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;
}
Output:
michi@michi-laptop:~$ ./program
******
Your Password is passwd
The getch
function needs some fix, but at least you get an Idea.
Upvotes: 1