簡體   English   中英

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中,存在如下輸入:

輸入索引和數字2 1

這是正確的

輸入索引和數字2

它只有1個值,並且程序在這里阻塞以等待其他輸入,我應該弄清楚並輸出“錯誤,請重試”

輸入索引和數字1 2 3

這也是不正確的,因為有兩個以上的輸入值。 同樣,我應該弄清楚並輸出“錯誤,然后重試”

該如何處理?

您應該使用cin.getline作為輸入。

然后將字符串拆分為子字符串並計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM