C++检测回车键问题:掩码用户输入时回车键仍被识别为字符
Hey there! Let's sort out this password masking issue you're facing. The main problem here is that when you press Enter in a Windows console, _getch() returns '\r' (carriage return) instead of '\n' (newline). Your current code checks for '\n', which never matches, so the Enter key gets added to your password string and an extra * is printed instead of breaking the loop.
Here's the corrected, improved version of your code, with explanations:
#include <iostream> #include <string> // Required for std::string #include <conio.h> int main() { std::cout << "Password: "; std::string passwd; // Declare the password storage variable (missing in your original code) char c; // Mask password input loop while ((c = _getch())) { // Catch the Enter key (Windows uses '\r' for physical Enter presses) if (c == '\r') { break; } // Optional: Handle backspace to let users correct their input else if (c == '\b') { if (!passwd.empty()) { passwd.pop_back(); // Remove the last character from the password // Visually erase the last *: backspace, overwrite with space, backspace again std::cout << "\b \b"; } continue; } passwd.push_back(c); _putch('*'); // Print mask character } // Add a newline to move the cursor to the next line after input std::cout << '\n'; // For testing only: Never print the actual password in production! std::cout << "You entered: " << passwd << std::endl; return 0; }
Key Fixes & Improvements:
- Enter Key Detection: Swapped the check from
'\n'to'\r'—this matches what_getch()actually returns when you press Enter on Windows. - Variable Declaration: Added
std::string passwd;and included the<string>header (your original code was missing this, which would cause a compile error). - Backspace Support: Added optional logic to handle backspace presses, so users can delete characters they typed by pressing Backspace—this makes the input feel much more natural.
- Clean Line Break: Added
std::cout << '\n';after the loop to move the cursor to a new line, so subsequent output doesn't sit right next to the password masks.
Note: _getch() is a Windows-specific function from <conio.h>. If you need cross-platform password masking, you'd need to use alternative methods (like reading from stdin with terminal settings modified), but this works perfectly for Windows environments.
内容的提问来源于stack exchange,提问作者coxijr

