C++ 整数输入仅限于四位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14514412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:23:55  来源:igfitidea点击:

Integer input restricted to four digits only

c++input

提问by B.K.

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++.

我正在做一个问题,它要求输入一个仅由四位数字组成的帐号。这必须使用基本的初学者 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....

我需要想办法将整数的输入限制为四位数。用户应该能够输入 0043 或 9023 或 0001 并且它应该是一个可接受的值....

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

我想我知道如何用字符串来完成它.... getline(cin,input) 然后检查是否 input.length()==4?

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

但我不知道我什至如何用整数输入来做到这一点。

采纳答案by Rapptz

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::vectormight be beneficial. You can do this easily (loop unrolling was for clarity):

如果您想以整数形式存储它,将整数保存在 an 中std::vector可能是有益的。你可以很容易地做到这一点(循环展开是为了清楚起见):

#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

你可以看到它在这里运行

回答by Keith

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

请注意,如果0043旨在不同于43,然后输入是不是其实是一个数字,而是数字字符串,就像一个电话“号码”。

Read the line as a string input.

将该行作为字符串读取input

Check that the length of inputis 4.

检查 的长度是否input4

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

检查字符串中的每个字符是否为<= '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;
}

回答by Code-Apprentice

I like your idea to use a stringas 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.

我喜欢你使用 astring作为输入的想法。这是有道理的,因为帐户“编号”只是一个标识符。您不会在计算中使用它。通过if (sizeof(input)==4)我认为你正试图检查的长度string。这样做的正确方法是if (input.length() == 4)。这将检查用户是否输入了 4 个字符。现在您需要确保每个字符也是一个数字。您可以利用数字字符的 ASCII 代码按您预期的顺序排列这一事实,轻松完成此操作。因此if (input[i] >= '0' && input[i] <= '9')将使用适当的 for 循环来解决索引i。此外,您可能需要某种循环,它会继续要求输入,直到用户输入被认为正确的内容为止。

Edit:

编辑:

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

作为检查每个字符是否为数字的替代方法,您可以尝试将字符串转换为intwith int value = atoi(input.c_str());。然后,您可以轻松检查它是否int为四位数或更少位数。

回答by Christian Mark

// 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.

类似于这个帖子。然后你可以调用这个函数来检查输入是否为 4 位数字。

回答by emartel

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.

通过这种方式,您可以立即优雅地处理无效字符。使用字符串时,输入只会在用户点击 时进行验证Enter

回答by B.K.

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):

所以我正在研究如何使用整数类型来获取输入,并查看了 char ......因为它在技术上是最小的整数类型,它可以用来获取代码......我能够想出这个,但它肯定还没有完善(我不确定是否可以):

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.

因此,循环一直持续到收集到 4 个字符。嗯,理论上应该。但它不起作用。它会在 2 位数、5 位数等处停止……我认为这可能是 cin.get() 抓取空白的性质,不确定。