-
cin.get problem
hi,
in code below cin.get() doesn't work correctly (maybe I'm mistaken)
Code:
#include <iostream>
#include <string>
using namespace std;
void getPassword(void);
bool Login(string, string);
int main
{
string uname;
string pass;
int cmd;
while (true)
{
cout << "Select your choose: " << endl
<< " 1. Login" << endl
<< " 2. What evere!" << endl
<< " 3. Exit" << endl;
cin >> cmd;
switch (cmd)
{
case 1:
cin.ignore();
cout << "Enter username: ";
getline(cin, username);
cout << "Enter Passwoed: ";
password = getPassword();
if (!Login(username, password))
{
cout << "> Username or Password was wrong!" << endl
<< "> Press Enter to continue" << endl;
cin.get(); // problem is here: I should press Enter twice!!?
cout << endl; // and what ever cout here will be ignored
break;
}
break;
case 2:
// do something
break;
case 3:
return 0;
break;
}
}
}
first time I press Enter, cursor will come at beginning of line. and next time, new line will overwrite on what would output in next line
I have tried different solution I found over internet but cannot solve this.
thanks in advance
-
> password = getPassword();
I see
string pass;
but no password.
Also, where is getPassword() implemented?
Does it leave the input stream in a nice clean state, like getline() does?
Or does it leave random garbage on the stream, leaving you to press return a few times?
-
this is getPassword function, and problem is exactly because of it.
How should I solve it?
Code:
string getPassword()
{
string result;
// Set the console mode to no-echo, not-line-buffered input
DWORD count;
HANDLE ih = GetStdHandle(STD_INPUT_HANDLE);
HANDLE oh = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleMode(ih, ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
// Get the password string
char c;
while (ReadConsoleA(ih, &c, 1, &count, NULL) && (c != '\r') && (c != '\n'))
{
if (c == '\b')
{
if (result.length())
{
WriteConsoleA(oh, "\b \b", 3, &count, NULL);
result.erase(result.end() -1);
}
}
else
{
WriteConsoleA(oh, "*", 1, &count, NULL);
result.push_back(c);
}
}
// Restore the console mode
SetConsoleMode(ih, (ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
cout << endl << endl << setw(70) << setfill('-') << "-" << endl << endl;
return result;
}
-
> while (ReadConsoleA(ih, &c, 1, &count, NULL) && (c != '\r') && (c != '\n'))
If you're expecting both \r and \n, then this loop will leave one of them behind.
Figure out which one comes last, then exit only on that one.