How to get a password with a CLI program?

风格不统一 提交于 2019-12-11 13:48:45

问题


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. C command-line password input
How to mask password in c?
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?


回答1:


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 ;)



回答2:


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.



来源:https://stackoverflow.com/questions/4050757/how-to-get-a-password-with-a-cli-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!