如果不需要某些数字,如何拒绝整数

时间:2016-10-17 05:05:21

标签: c++

如果我想要一个整数输入,但如果它包含任何数字2或3,它将被拒绝。

例如,输入23564将无效。

我正在考虑使用do-while循环来解决这个问题,但是如何让它来读取各个数字。

4 个答案:

答案 0 :(得分:0)

您可以使用以下内容获取数字的最后数字:

unsigned int number = 23456;
unsigned int digit = number % 10;  // gives 6

您可以使用以下方式进一步“移动”所有数字:

number = number / 10;              // gives 2345

换句话说,是的,你可以使用你建议的方法来做到这一点:

bool has2Or3(unsigned int number) {
    // Do until no more digits left.

    while (number != 0) {
        // Get last digit, return true if 2 or 3.

        int digit = number % 10;
        if ((digit == 2) || (digit == 3)) {
            return true;
        }

        // Prepare to get next digit.

        number = number / 10;
    }

    // If NO digits were 2 or 3, return false.

    return false;
}

另一种方法是简单地将其转换为字符串并使用字符串函数来查看它是否包含特定数字,例如:

bool has2Or3(unsigned int number) {
    // Get number as string (via string stream).

    std::stringstream ss;
    ss << number;
    std::string s = ss.str();

    // If contains 2, return true, else continue.

    if (s.find("2") != std::string::npos)
        return true;

    // If contains 3, return true, else return false.

    return (s.find("3") != std::string::npos);
}

答案 1 :(得分:0)

看看这里:

PTTL

答案 2 :(得分:0)

如果您不太关心性能,可以将整数转换为字符串并查找数字。这比提取最后一位数字并进行比较要慢。

std::string str = std::to_string(number);
auto found2 = str.find('2');
auto found3 = str.find('3');

//number is valid if it doesn't have a 2 or a 3
bool isValid = found2 == std::string::npos && found3 == std::string::npos;

答案 3 :(得分:0)

不是直接将输入读入整数类型,而是将其读入std::string。然后检查不需要的数字很简单;如果字符串通过测试,则将其转换为整数:

int get_value() {
    std::string bad = "23";
    std::string input = "2"; // start with bad input
    while (std::find_first_of(input.begin(), input.end(),
        bad.begin(), bad.end()) != input.end()) {
        std::cout << "Gimme a number: ";
        std::cin >> input;
    }
    return std::stoi(input);
}