Code:
#include <iostream>
using namespace std;
string pw; //The variable in which the password is stored.
int endprogram; //A way to keep the program open.
int exitprog;
int main()
{
cout<<"Enter password: \n";
cin>> pw; //Places the user input in the string variable pw.
for(; ;) { //An unconditional loop intended as a way to have multiple attempts.
if(pw == "pw") { //If the password is "pw",
cout<< "Welcome.\n"; //print this.
cin>> exitprog; //Keeping the program open,
if (exitprog == 1) { //and compares user input to 1
exit(0); //Exits program
}
}
else { //Otherwise,
cout<< "Try again.\n"; //print this and begin the loop again so that the password may be entered.
cin>> endprogram; //^
}
}
}
It's obvious the program doesn't work but I'm not sure what to do to make it work. I want it to check whether pw is equal to "pw" and if it's not, print "Try again", and consequently "Enter password" again. Right now if you type in the wrong password it prints "Try again" and if you try to type in anything after that it loops that message infinitely.
Also I wonder if someone can tell me how to detect keypresses by the user, because if(exitprog == 1) is a quite awkward way to go about it. Instead I want a "Press any key to terminate" sort of thing.