### validate integer length?

Hi. I need help adding input validation to my program.

When the user inputs his account number, it should only be 5 digits long.

 ``123456789101112131415161718192021222324252627282930313233343536`` ``````//Begin execution int main(){ //Declare variables unsigned short bal,totChk, totDep;//account number,balance, total checks, total deposits float newBal, ovrBal;//new balance, overdrawn balance if account is overdrawn int accNum; //Prompt reader for inputs cout<<" This program will determine if you " <<" have overdrawn your checking account "<>accNum; cout<<" Enter your balance at the beginnning of the month "<>bal; cout<<" Enter the total of all checks written this month "<>totChk; cout<<" Enter the total of all deposits credited to your account this month "<>totDep; //Calculate new balance newBal=bal+(totDep-totChk); cout<<" Total Balance for account number "<

 ``1234`` ``````if(accNum<0&&accNum<9999){ cout<<" Account numbers are five digits long "<>accNum; }``````

But it still allows me to enter more and less than 5 digits.

I'd appreciate the help
`if(accNum<0&&accNum<9999)`

This reads like: if accNum is less than 0 and accNum is less than 9999.
In other words, it means it will never be triggered unless accNum is less than 0.
so would this work?
`if(accNum>0&&accNum<9999)`
Last edited on
What happened when you tried it?
It validates it the first time if i put a number with less than 5 digits and then the second it does not validate it.
It doesn't validate it for numbers bigger than 5 either
So when you entered a number less than 9999 it asked for another and then went to the next statement right? If I understand right, it's not supposed to ask again. So first you need to reverse the condition

`if(accNum < 0 || accNum > 9999)`

Also to get it to continue asking until a right number is input, you need to use a loop or it will only ask once before going to the next statement.
Would it be a for loop or while loop?
for loops are used mainly when you know how many times you need to iterate through the loop so that's not really appropriate in this case. Most people would use a do/while loop, but I generally would just use a while loop for this.

Also, those values don't work to only accept 5 digit numbers, but I'm sure you can figure out how to change them on your own.
5 digits could also includes negative values.
True, but can you give an instance of an account number that does? It would be more likely that it contained letters and my first thought was to use string instead of int, that way you only needed to check its length. In my opinion that's over complicating this problem though.
Topic archived. No new replies allowed.