簡體   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