In: Computer Science
C++ Language
Create Login Register program without open .txt
file
simple program also if you can hide password input
option menu
1) Login
2) Register
3) exit
/* Following code is for changing the input visibility for windows nd linux*/
// checks if its windows or linux
#ifdef WIN32
// if windows then include windows.h header file
#include <windows.h>
#else
// if not windows then include following for unix type os
#include <termios.h>
#include <unistd.h>
#endif
// changes the visibility,if true then visible
void ChangeInputVisibility(bool show = true)
{
// if windows
#ifdef WIN32
// get console handler
HANDLE stdinHandler = GetStdHandle(STD_INPUT_HANDLE);
// stores echoinput env variable dword
DWORD currentMode;
GetConsoleMode(stdinHandler, ¤tMode);
// changes consolemode ECHO to show/hide inputs
if( !show )
currentMode &= ~ENABLE_ECHO_INPUT;
else
currentMode |= ENABLE_ECHO_INPUT;
// sets the new stdinHandler mode
SetConsoleMode(stdinHandler, currentMode);
#else
// changes tty ECHO to show/hide inputs
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if( !show )
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
#endif
}
/* following is the basic code*/
#include<iostream>
#include<string>
using namespace std;
int main(){
// stores user's selectio
int option;
// holds username , password, current password
string userName="",password,loginPassword;
// repeats untill user seletcs exit
while(true){
// show menu
cout << "\n\noption menu" << endl;
cout << "1) Login" << endl;
cout << "2) Register " << endl;
cout << "3) exit" << endl;
cout << "select an option: ";
// gets option
cin >> option;
switch(option){
// for option 1
case 1:
// if there is already user registered ask password
if(userName!=""){
// asks password
cout << "Enter password: ";
// hide inputs
ChangeInputVisibility(false);
cin >> loginPassword;
// show inputs
ChangeInputVisibility(true);
// if its correct password,then show username
if(password==loginPassword){
cout << "Logged in as " << userName;
}else{
// else invalid password
cout << "Password invalid" << endl;
}
}else{
// if there is no existing user name
cout << "No account registered" << endl;
}
break;
// if user select option 2
case 2:
// ask user name and password
cout << "Enter username: ";
cin >> userName;
cout << "Enter password: ";
// hide inputs
ChangeInputVisibility(false);
cin >> password;
// show inputs
ChangeInputVisibility(true);
break;
// if user select 3
case 3:
// exit the programm
return 0;
break;
// for all other inputs,show invalid option
default:
cout << "Invalid input!" << endl;
}
}
return 0;
}
Code screenshot:
Output:
PS: If you have any doubts/problems please comment here.Thank You