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

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

下面是我的 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 中,存在如下输入:

input the index and num 2 1

这是正确的

input the index and num 2

它只有 1 个值,程序阻塞在这里等待另一个输入,我应该弄清楚并输出 "error, try again"

input the index and num 1 2 3

这也是不正确的,因为有超过 2 个输入值。同样,我应该弄清楚并输出 "error, try again"

如何处理?

您应该使用 cin.getline 作为输入。

然后split the string into substrings数一数。