4 digit pin

im wondering how I can ask the user to input a 4 digit pin and it can only be 4 numbers and if its not 4 numbers it it will give them an error and let them retype the pin but im stuck on how to do it any help would be appreaciated

this as well is in a function which is called void welcomeMessage()
1
2
3
4
5
6
7
8
9
10
11
  int pin=0;
if (pin==1234)
{
cout<<"Please enter a 4 digit pin: ";
cin>>pin;
}
else if(pin<1234||pin>1234)
{
cout<<"NOT the correct pin"<<endl;
}
1000 <= pin <= 9999
so do I just place those numbers in the code I have up top??
if(pin>999 && pin <=9999)
cout << "pin is ok";
else
cout << "wrong pin";
Last edited on
ok cool thanks and one more question if they enter the wrong pin how can I make it so they have to enter the pin again and wont let the program run until they put the correct pin??
1
2
3
4
5
int r=0;
do {
    std::cout << "Please enter a 4-digit pin: ";
    std::cin >> r;
} while(r < 1000 || r >= 10000);
the only problem Is if they enter more than 4 numbers or less it will give the invalid pin message but it will continue to run the program and I don't want it to run until they enter the right pin.
this is what I have
1
2
3
4
5
6
7
8
9
10
11
12
13
 cout<<"Enter your 4 digit pin please: ";
  cin>>pin;
 if(pin>999 && pin<=9999)
   {

   }
 else
   {
      cout<<"Invalid Pin: "<<endl;//<<pin<<"."<<endl;
     return -1;
    }

Last edited on
Did you try the last one?
how could I display and error message saying it wasn't the correct pin?? cause if I were to enter invalid pin after the cin>>r; it runs but after it displays invalid pin how could I fix that??
Last edited on
closed account (SNybRXSz)
It's pretty simple. You want a loop that runs until a pin in correctly input. EssGeEich showed yo usomething like this with no error message. If you want the error message you could do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int pin = 0;

//get the pin for the first time.
cout<<"Enter your 4 digit pin please: ";
cin>>pin;

//if the pin is smaller then 1000 (3 digits or less) or greater then 9999 (5 digits or more) have the user re input their pin and give an error
while (pin<1000 && pin>9999)
{
    cout << "ERROR: Invalid Pin: " << endl;
    cout<<"Enter your 4 digit pin please: ";
    cin>>pin;

}

//continue on with code to check the pin etc. 

thanks everyone helped alot
If I were the professor I would be asking, "What about pins that begin with zeros? Your solutions won't work. 0001 is a four-digit, thus valid pin.
as PCrumley48 noted, the input can be taken as a string, check it's length is 4.
and it contains only digits. (can a pin be non-digit ?)
Topic archived. No new replies allowed.