簡體   English   中英

僅接受整數輸入

[英]Accept only integer to input

我發現這個類似的問題被問了很多遍了,但是我仍然找不到我的解決方案。

就我而言,我想在用戶輸入1到5之間的數字時顯示一些內容,當他輸入諸如“ 3g”,“ 3。”,“ b3”和任何浮點數之類的錯誤內容時,給出一個錯誤。

我嘗試了下面的代碼,但它創建了許多其他問題。 就像如果我進入3g3.5 ,它只會采取3而忽略其他,因此(!cin)不會在所有的工作。

其次,如果我輸入類似字符的內容,則__userChoice將自動轉換為0 ,並且程序將輸出"Please select a number from 1 to 5." 而不是"Invalid input, please input an integer number.\\n" ,這是我想要的。

cout << "Please select: ";
cin >> __userChoice;
if (__userChoice > 0 && __userChoice < 5) {
    cout << "You select menu item " << __userChoice <<". Processing... Done!\n";
}
else if (__userChoice == 5) {
    Finalization(); //call exit
}
else if (__userChoice <= 0 || __userChoice > 5) {
    cout << "Please select a number from 1 to 5.\n";
}
else (!cin) {
    cout << "Invalid input, please input an integer number.\n";
}
cin.clear();
cin.ignore(10000, '\n');

如果發生故障,不能保證operator>>會輸出有意義的整數值,但是您不會在評估__userChoice之前檢查故障,並且永遠不會達到if s的else (!cin)檢查結構的方式。 但是,即使operator>>成功,您也不會檢查用戶是否輸入了多個整數。

要執行您要的操作,您應該先使用std::getline() std::cin讀為std::string ,然后使用std::istringstreamstd:stoi() (或等效)進行轉換帶有錯誤檢查的int string

例如:

bool strToInt(const std::string &s, int &value)
{
    std::istringstream iss(s);
    return (iss >> value) && iss.eof();

    // Or:

    std::size_t pos;
    try {
        value = std::stoi(input, &pos);
    }
    catch (const std::exception &) {
        return false;
    }
    return (pos == input.size());
}

...

std::string input;
int userChoice;

std::cout << "Please select: ";
std::getline(std::cin, input);

if (strToInt(input, userChoice))
{
    if (userChoice > 0 && userChoice < 5)
    {
        std::cout << "You selected menu item " << userChoice <<". Processing... Done!\n";
    }
    else if (userChoice == 5)
    {
        Finalization(); //call exit
    }
    else
    {
        std::cout << "Please select a number from 1 to 5.\n";
    }
}
else
{
    std::cout << "Invalid input, please input an integer number.\n";
}

暫無
暫無

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

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