B.K.
B.K.

Reputation: 10162

Integer input restricted to four digits only

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.

Upvotes: 6

Views: 28181

Answers (6)

Code-Apprentice
Code-Apprentice

Reputation: 83557

I like your idea to use a string as the input. This makes sense because an account "number" is simply an identifier. You don't use it in calculations. By if (sizeof(input)==4) I think you are trying to check the length of the string. The correct way to do this is if (input.length() == 4). This will check that the user inputs 4 characters. Now you need to make sure that each of the characters is also a digit. You can do this easily by taking advantage of the fact that the ASCII codes for digit characters are ordered as you expect. So if (input[i] >= '0' && input[i] <= '9') will do the trick with an appropriate for loop for the index i. Also, you probably need some kind of loop which continues to ask for input until the user enters something which is deemed to be correct.

Edit:

As an alternative to checking that each character is a digit, you can attempt to convert the string to an int with int value = atoi(input.c_str());. Then you can easily check if the int is a four-or-less-digit number.

Upvotes: 1

B.K.
B.K.

Reputation: 10162

So I was going over how I can use an integer type to get the input, and looked at char... since it's technically the smallest integer type, it can be used to get the code... I was able to come up with this, but it's definitely not refined yet (and I'm not sure if it can be):

int main() {
    int count=0;

    while(!(count==4)){
        char digit;
        cin.get(digit);
        count++;
    }

    return 0;
}

So, the loop keeps going until 4 characters are collected. Well, in theory it should. But it doesn't work. It'll stop at 2 digits, 5 digits, etc.... I think it could be the nature of cin.get() grabbing white space, not sure.

Upvotes: 0

emartel
emartel

Reputation: 7773

You probably want your code to be responsive to the user input, so I would suggest getting each character at a time instead of reading a string:

std::string fourDigits;
char currentDigit;

std::cout << "Enter 4 digits\n";
for(int i = 0; i < 4; ++i)
{
    currentDigit = getch();
    if(isdigit(currentDigit))
    {
        fourDigits += currentDigit;
        std::cout << currentDigit; // getch won't display the input, if it was a PIN you could simply std::cout << "*";
    }
    else
    {
            // Here we reset the whole thing and let the user know he entered an invalid value
        i = 0;
        fourDigits = "";
        std::cout << "Please enter only numeric values, enter 4 digits\n";
    }
}

std::cout << "\nThe four digits: " << fourDigits.c_str();

This way you can handle gracefully invalid character instantly. When using strings, the input will only be validated once the user hits Enter.

Upvotes: 0

Rapptz
Rapptz

Reputation: 21317

Something like this should work. Once the user enters something with exactly four characters you can validate it. The rest of the logic is up to you.

#include <iostream>
#include <string>

int main() {
    std::cout << "Enter a PIN Number: ";
    std::string pinStr;
    while(std::getline(std::cin,pinStr) && pinStr.size() != 4) {
        std::cout << "Please enter a valid value\n";
    }
}

Should you want to store it in an integer form, holding the integers in an std::vector might be beneficial. You can do this easily (loop unrolling was for clarity):

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::cout << "Enter a PIN Number: ";
    std::string pinStr;
    while(std::getline(std::cin,pinStr) && pinStr.size() != 4 ) {
        std::cout << "Please enter a valid value\n";
    }
    std::vector<int> pin;
    pin[0] = pinStr[0] - '0';
    pin[1] = pinStr[1] - '0';
    pin[2] = pinStr[2] - '0';
    pin[3] = pinStr[3] - '0';

    //pin now holds the integer value.
    for(auto& i : pin)
        std::cout << i << ' ';
}

You can see it running here

Upvotes: 1

Keith
Keith

Reputation: 6834

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;
}

Upvotes: 2

Mark
Mark

Reputation: 8441

// generic solution
int numDigits(int number)
{
    int digits = 0;
    if (number < 0) digits = 1; // remove this line if '-' counts as a digit
    while (number) {
        number /= 10;
        digits++;
    }
    return digits;
}

similar to this post. Then you can call this function to check if the input is 4 digits.

Upvotes: 0

Related Questions