简体   繁体   English

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

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

below is my C++ code: 以下是我的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);
    }
}

And now there is a shell to run this code, but in the shell, there exist input like below: 现在有一个运行该代码的shell,但是在shell中,存在如下输入:

input the index and num 2 1 输入索引和数字2 1

this is the correct one 这是正确的

input the index and num 2 输入索引和数字2

it just have 1 value, and the program blocked here to wait for another input, i should figure that out and output "error, try again" 它只有1个值,并且程序在这里阻塞以等待其他输入,我应该弄清楚并输出“错误,请重试”

input the index and num 1 2 3 输入索引和数字1 2 3

this is also incorrect because there are more than 2 input value. 这也是不正确的,因为有两个以上的输入值。 the same, I should figure that out and output "error, try again" 同样,我应该弄清楚并输出“错误,然后重试”

How to deal with this? 该如何处理?

You should use cin.getline for your input instead. 您应该使用cin.getline作为输入。

Then split the string into substrings and count them. 然后将字符串拆分为子字符串并计数。

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

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