Whats an easy way I can store the password the user inputs while still keeping the password hidden?
char password[9];
int i;
printf("Ent开发者_C百科er your password: ");
for (i=0;i<9;i++)
{
password[i] = getch();
printf("*");
}
for (i=0;i<9;i++)
printf("%c",password[i]);
getch();
}
I wanna store the password so I can do a simple if (password[i] == root_password)
so the proper password continues on.
Your problem appears to be that you're not checking for newline '\n' nor end-of-file.
printf("Enter your password: ");
char password[9];
int i;
for (i = 0; i < sizeof password - 1; i++)
{
int c = getch();
if (c == '\n' || c == EOF)
break;
}
password[i] = c;
printf("*");
}
password[i] = '\0';
This way, password will end up being an ASCIIZ string, suitable for printing with puts
, printf("%s", password)
, or - crucially...
if (strcmp(password, root_password)) == 0)
your_wish_is_my_command();
Note that we read at most 8 characters into the password as we need one extra character for the NUL terminator. You could increase that if you wanted.
You need to use the console API in Windows. Below is a snippet that disables echoing in the console window. The function SetConsoleMode()
is used to control the echoing (among other things). I save the old mode, so that I can restore the console once the password has been retrieved.
Also, the *ConsoleMode()
functions need a handle to the console input buffer. How you can get a handle to these buffers is described in the MSDN documentation of CreateFile()
.
int main(int argc, char* argv[])
{
char password[100] = { 0 };
printf("Enter your password: ");
HANDLE hConsole = ::CreateFile("CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
DWORD dwOldMode;
::GetConsoleMode(hConsole, &dwOldMode);
::SetConsoleMode(hConsole, dwOldMode & ~ENABLE_ECHO_INPUT);
bool bFinished = false;
while(!bFinished) {
if(!fgets(password, sizeof(password) / sizeof(password[0]) - 1, stdin)) {
printf("\nEOF - exiting\n");
} else
bFinished = true;
}
::SetConsoleMode(hConsole, dwOldMode | ENABLE_ECHO_INPUT);
printf("\nPassword is: %s\n", password);
return 0;
}
Since we are in C++ and Windows do this:
#include <iostream>
#include <string>
#include <conio.h> //_getch
#include <Windows.h> //VK_RETURN = 0x0D
using namespace std;
string read_password()
{
string pass;
cout << "Enter your password: ";
int character = 0;
while(VK_RETURN != (character = _getch()) )
{
cout << '*';
pass += static_cast<char>(character);
}
cout << std::endl;
return pass;
}
int main ()
{
string root_password = "anypass123";
string pass = read_password();
if (pass == root_password)
{
cout << "password accepted" << endl;
}
return 0;
}
compiled & tested
精彩评论