Password Input in Console : How to Make It Look Like Password

Hi, here is a small code to implement password like look in C++ console input, there is nothing much to say, just that you can use it as a function and return the value as string which will be the password. You can set the character printed instead of real input to make it look like whatever you prefer. Please let me know if there is any error or logical mistake in code.
 #include <iostream>  
 #include <string>  
 #include <conio.h>  
 using namespace std;  
 void main(){  
  string password;  
  char temp = 0;  
  while (true){  
  temp = _getch();  
  if (temp == 13)  
   break;  
  if ((int)temp == 8){  
   password = password.substr(0, password.length()-1);  
  }  
  else{  
   password = password + temp;  
  }  
  cout << '\r';  
  for (int i = 0; i <= password.length(); i++)  
  cout << ' ';  
  cout << '\r';  
  for (int i = 0; i < password.length(); i++){  
   cout << '*';  
  }  
  }  
  system("cls");  
  cout << password << endl;  
  system("pause");  
 }  

Here is it like a function:
 #include <iostream>  
 #include <string>  
 #include <conio.h>  
 using namespace std;  
 string getPassword();  
 void main(){  
  cout << "Enter your password:" << endl;  
  cout << getPassword() << endl;  
  system("pause");  
 }  
 string getPassword(){  
  string password;  
  char temp = 0;  
  while (true){  
  temp = _getch();  
  if (temp == 13)  
   break;  
  if ((int)temp == 8){  
   password = password.substr(0, password.length() - 1);  
  }  
  else{  
   password = password + temp;  
  }  
  cout << '\r';  
  for (int i = 0; i <= password.length(); i++)  
   cout << ' ';  
  cout << '\r';  
  for (int i = 0; i < password.length(); i++){  
   cout << '*';  
  }  
  }  
  cout << endl;  
  return password;  
 }  

You can use this function getPassword() in your program. Enjoy!

Comments

Popular posts from this blog

C++ Console : Basic Graphic Techniques

C++ Console : Change Font Size

C++ Console : Color