繁体   English   中英

C ++如何从Shell检查输入的数量

[英]C++ How to check the number of the input from Shell

void test() {
    int i ,j;
    cout << "enter the i and j" << endl;
    cin >> i >> j;
    if (j <= 5 && j > 0 && i > 0 && i <= 9) {
        cout << "right" <<endl;
    } else {
        cout << "error" << endl;
        test();
    }
}

int main(int argc, const char * argv[]) {
    test();
}

如何从命令行检查输入是否完全正确?

下面是一些错误的测试,我们应该在else部分中运行代码。

foo ags

但是命令行中的结果是28行错误信息。 但是我想要的只是一个代码行显示“错误”

有什么问题?

另一个

以下是我的C ++代码:

void test(int array[], int length) {
    int index;  // the index of heap array that human want to modify
    int num;  // the number of heap in the index position
    cout << "input the index and num" << endl << flush;
    string si,sj;
    try{
        cin >> si >> sj;
        index = stoi(sj);
        num = stoi(si);
    }catch(std::exception e){
        cout << "error, try again" << endl;
        test(array, length);
    }
    if (index <= length && index > 0 && num > 0 && num <= array[index - 1]) {
        array[index - 1] -= num;
        // print(array, length);
    } else {
        cout << "error, try again" << endl;
        test(array, length);
    }
}

现在有一个运行该代码的shell,但是在shell中,存在如下输入:

输入索引和数字2 1

这是正确的

输入索引和数字2

它只有1个值,并且程序在这里阻塞以等待其他输入,我应该弄清楚并输出“错误,请重试”

输入索引和数字1 2 3

这也是不正确的,因为有两个以上的输入值。 同样,我应该弄清楚并输出“错误,然后重试”

该如何处理?

首先,您需要将输入读取为字符串,然后使用std :: stoi将字符串转换为int来检查错误。 假设您只需要“错误”消息,请使用try-catch块仅捕获std :: exception并输出“错误”。 其次,要在出现错误的情况下重复调用test(),则需要使用某种lopp,并且不要从test()内部调用test()。 这种技术称为递归调用,用于其他目的,而不是简单的重复。 我已经修改了您的test()函数以返回bool值,如果成功则返回true,如果出错则返回false,然后从while()循环中调用它,如果返回false则将重复调用。 关于第二个问题,您需要分别输入数字,每个数字都在不同的行上。 该程序将能够单独检查每个数字。 看到代码:

#include <string>
#include <iostream>
bool test() {
    int i ,j;
    std::string si,sj;
    try{
        cout << "enter i:" << endl;
        cin >> si;
        i = std::stoi(si);
        cout << "enter j:" << endl;
        cin >> sj;
        j = std::stoi(sj);
    }catch(std::exception e){
        cout << "error";
        return false;
    }
    if (j <= 5 && j > 0 && i > 0 && i <= 9) {
        cout << "right" <<endl;
        return true;
    } else {
        cout << "error" << endl;
        return false;
    }
}

int main(int argc, const char * argv[]) {
    while(!test()){}
}

cin >> i >> j; 只是跳过前导空格,然后读取由空格分隔的两个格式化的int值。 如果您在示例中输入的内容更多,其余的将保留在输入流缓冲区中。 如果再次调用test() ,则cin从该缓冲区读取。

您可以使用cin.ignore(numeric_limits<streamsize>::max())解决该问题,因为它会清除缓冲区。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM