简体   繁体   中英

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

below is my C++ code:

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:

input the index and num 2 1

this is the correct one

input the index and num 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"

input the index and num 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.

Then split the string into substrings and count them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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