I suggest something simple. Like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
bool Enter_pin(void); // 'void' is optional.
int main(void)
{
return(0);
}
bool Enter_pin(void)
{
char Correct_pin[5] = "0101";
char Given_pin[5] = { 0 }; // A
// Get the pin from the user
std::cin.read(Given_pin, 4); // B
// Compare the given pin with the correct pin
if(!std::strcmp(Given_pin, Correct_pin)) // C
return(true);
else return(false);
}
|
Program notes:
A) The way the braces are used here is called an
initialiser list. When a single value is placed within the braces, the first elements is set to that value, but the remaining elements are set to 0(zero). However, if too few values are placed within the list, the remaining values are set to 0 (zero). Don't forget that when you create a character array, make sure the array is 1 character larger (for the null-character).
B)
std::istream::read()[1] is a function that extracts
n bytes from the input buffer and places them within the array. In this case, 4 bytes (or characters) are read from the input buffer and placed within
Given_pin.
C)
std::strcmp()[2] is a function within the
<cstring> header. It compares two strings together. It returns zero if the strings match; non-zero otherwise. I guess you're wondering why you can't do this:
if(Given_pin == Correct_pin)
The reason why is because you won't be comparing strings, but the address of the strings. Unless the strings are situated at the exact same place in memory, the comparison will always be false. Another reason is because the compiler's doesn't know the length of the arrays.
I hope I didn't confuse you.
References:
[2] http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
[1] http://www.cplusplus.com/reference/iostream/istream/read/
Wazzak