Hi everyone,
I am getting some problems with validating a postal code in C++. It will catch some of the bad data entered if it's not in 'L#L#L#L#' format but not all of it and that's where I'm stuck. I need to check the length of the postal code to ensure that it is just 6 characters and then I need to make sure the format of the 6 characters is 'letter-number-letter-number-letter-number'.
Here is the code segment for the validation that I have at this point:
Code:
string pcode;
int i;
int pcodelen;
int pcode_flag = 0;
while (pcode_flag == 0) {
cout << "\nEnter your postal code: "; cin >> pcode;
pcodelen = pcode.length();
if (pcodelen != 6) {
pcode_flag = 0;
break;
}
else {
for (i = 0; i < 6; i++) {
if (i % 2 == 0) {
if (pcode[i] < 65 || pcode[i] > 90) {
pcode_flag = 0;
break;
}
else {
pcode_flag = 1;
}
}
else {
if (pcode[i] < 48 || pcode[i] > 57) {
pcode_flag = 0;
break;
}
else {
pcode_flag = 1;
}
}
}
}
}
As I said above, it is catching some of the errors in the inputted data but it's not foolproof yet and is still allowing invalid postal codes to be accepted.
If anyone can tell me how this needs to be revised so that it works fully and correctly, it would be greatly appreciated.
Thanks.