Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer input restricted to four digits only

Tags:

c++

input

I'm doing a problem where it asks to input an account number, which consists only of four digits. This has to be accomplished with basic beginner C++.

I need to figure out a way to restrict the input of the integer to four digits. A user should be able to put in 0043 or 9023 or 0001 and it should be an acceptable value....

I think I know how to accomplish it with a string.... getline(cin,input) and then check if input.length()==4?

But I've no idea how I would even do this with an integer input.

like image 968
B.K. Avatar asked Jan 25 '13 02:01

B.K.


1 Answers

Note that if 0043 is intended to be distinct from 43, then the input is not in fact a number, but a digit string, just like a telephone "number".

Read the line as a string input.

Check that the length of input is 4.

Check that each character in the string is <= '9' and >= '0'.

Something like:

std::string read4DigitStringFromConsole()
{
    bool ok = false;
    std::string result;
    while (!ok)
    {
        std::cin >> result;
        if (result.length() == 4)
        {
            bool allDigits = true;
            for(unsigned index = 0; index < 4; ++index)
            {
                allDigits = allDigits && ( 
                    (result[index] >= '0') && 
                    (result[index] <='9') 
                    );
            }
            ok = allDigits;
        }
    }
    return result;
}
like image 96
Keith Avatar answered Oct 31 '22 01:10

Keith