2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by cbrules3033
0

It's not really possible with standard C++ I/O. You need more control over keystrokes, and that means using non-standard functions. The most commonly known is getch. getch reads a scan code without echoing it to the screen:

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

int main()
{
  std::string password;
  int ch;

  while ((ch = getch()) != '\r') {
    password += (char)ch;
    std::cout.put('*');
  }

  std::cout << '\n' << password << '\n';
}

But remember that it's totally manual now. If you want to handle stuff like backspaces, your code needs to include logic for it:

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

int main()
{
  std::string password;
  int ch;

  while ((ch = getch()) != '\r') {
    if (ch == '\b') {
      // Remove the character from the string
      password = password.substr(0, password.size() - 1);

      // Remove the mask character too
      std::cout << "\b \b";
    }
    else {
      password += (char)ch;
      std::cout.put('*');
    }
  }

  std::cout << '\n' << password << '\n';
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.