Home >Backend Development >C++ >How Can I Read Passwords from Standard Input Without Echoing Them?

How Can I Read Passwords from Standard Input Without Echoing Them?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 16:24:10218browse

How Can I Read Passwords from Standard Input Without Echoing Them?

Reading Passwords from std::cin without Echoing

The need to read passwords from standard input without echoing the input characters arises regularly. To achieve this, it's essential to disable the echo on std::cin.

Windows and UNIX Differences

The method for disabling echo depends on the operating system. In Windows, the GetConsoleMode and SetConsoleMode functions are used, while in UNIX-like systems, tcgetattr and tcsetattr are employed.

Implementing the Solution

The provided code snippet includes an OS-agnostic function, SetStdinEcho, which allows toggling echo for std::cin. A sample usage is also provided, demonstrating how to read a password without echoing and then echo it when the user presses enter:

#include <iostream>
#include <string>

int main()
{
    SetStdinEcho(false);

    std::string password;
    std::cin >> password;

    SetStdinEcho(true);

    std::cout << password << std::endl;

    return 0;
}

This code ensures the user's password remains private while being entered and displayed upon successful input.

The above is the detailed content of How Can I Read Passwords from Standard Input Without Echoing Them?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn