views:

78

answers:

2

I am writing a Linux CLI program. I need to get a password from the user and, obviously, I don't want the password to be echoed to the console.

There are several solutions available here, but they are all for plain C. http://stackoverflow.com/questions/1786532/c-command-line-password-input
http://stackoverflow.com/questions/1754004/how-to-mask-password-in-c
http://stackoverflow.com/questions/1196418/getting-a-password-in-c-without-using-getpass-3

How can those be adapted for C++, using std::string instead of char[]?

What would be the most elegant C++ solution?

+2  A: 

Linux itself is written (mostly) in C, so anything you could find in C++ would only be an abstraction around a single C routine. Better to call the routine yourself, converting the input and result.

Ignacio Vazquez-Abrams
+1. Thank you..
augustin
+2  A: 

Use any of the plain C solutions:

std::string pass (100);  // size the string at your max password size (minus one)

func_to_get_pass(&pass[0], pass.size());
// function takes a char* and the max size to write (including a null char)

pass.resize(pass.find('\0'));

cout << "Your password is " << pass << ".\n"; // oops! don't show it ;)
Roger Pate
+1. Thank you for the code. I don't master this kind of simple things, yet. It's very useful.
augustin