c++ - 我们可以在 C++ 中限制用户输入吗?

标签 c++

问题是当用户输入 = 9999999999 时,控制台将返回所有值。
我想通过使用简单的 来限制这个输入否则如果 如果有人试图为 a, b = 9999999999 设置值,则用户必须收到我在代码中定义的警告。
我可以通过使用 double 而不是 int 来控制它,但这不是解决方案。

#include <iostream>
using namespace std;
main()
{
    int a, b, c, d;
    cout << "Enter Value for A: ";
    cin >> a;

    cout << "Enter Value for B: ";
    cin >> b;

    if (a > b)
        {
        cout << "A is Greater than B " << endl; //This will be printed only if the statement is True
        }
    else if ( a < b )
        {
        cout << "A is Less than B " << endl; //This will be printed if the statement is False
        }
        else if ( a, b > 999999999 )
        {
        cout << " The Value is filtered by autobot !not allowed " << endl; //This will be printed if the statement is going against the rules
        }
     else
        {
        cout << "Values are not given or Unknown " << endl; //This will be printed if the both statements are unknown
        }

    cout << "Enter Value for C: ";
    cin >> c;

    cout << "Enter Value for D: ";
    cin >> d;

    if (c < d)
    {
        cout << c << " < " << d << endl; //This will be printed if the statement is True
        }
        else if ( c > d )
        {
        cout << "C is Greater than D " << endl; //This will be printed if the statement is False
        }
        else
        {
        cout << c << " unknown " << d << endl; //This will be printed if the statement is Unknown
        }
}

最佳答案

这是一个确保有效输入的示例函数。我也让它包含了最小值和最大值,但您不一定需要它们,因为 999999999 将超出 int 的范围。无论如何,这会导致 cin失败。不过它会等待有效的输入。

int getNum( int min, int max ) {
    int val;
    while ( !( cin >> val ) || val < min || val > max ) {
        if ( !cin ) {
            cin.clear();
            cin.ignore( 1000, '\n' );
        }
        cout << "You entered an invalid number\n";
    }
    return val;
}

int main() {
    int a = getNum( 0, 12321 );
}

编辑:嗯,现在你只是修改了你的问题,使用简单的 else if 语句,改变答案。那么答案是否定的。自 cin会失败,您实际上无法进行检查。此外,自从 999999999 以来,它永远不会是真的。大于 INT_MAX在我能想到的任何实现上。

关于c++ - 我们可以在 C++ 中限制用户输入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59971939/

相关文章:

c++ - llvm clang 编译器上的 dynamic_cast 失败

c++ - 试图理解 C++ 标准中的 [class.qual]/2

在 Linux 机器中使用套接字发送和接收文件时出现 C++ 问题

C++从成员指针转换回持有类指针

c++ - 错误 LNK2019 : unresolved external symbol referenced in function _main visual c++

c++ - 在 Clang C++ 上使用 __super

c++浮点减法错误和绝对值

c++ - 从 char 数组到 std::string 的类型推导

c++ - 施放 ssize_t 或 size_t

c++ - 如何在现代 Opengl 中添加 View 矩阵