簡體   English   中英

在 C++ 中驗證整數輸入

[英]Validating Integer Input in C++

我正在嘗試驗證輸入,僅接受整數,並且它對於 4 之后的字母和小數點工作正常。例如,如果我輸入 1.22,它將只讀取第一個並進入不定式循環,但是當我輸入數字時,更大的是什么比4,例如5.55它工作得很好,我該如何解決這個問題? 謝謝並感謝您的幫助!

void Furniture::getSelection()
{
    do {
        cout << "\nWhich object would you like to measure:\n"
             << "1.Table\n"
             << "2.Stool\n"
             << "3.Bookshelf\n"
             << "4.Exit\n" << endl;   

        while(!(cin >> choice)) {
            cerr << "The format is incorrect!" << endl;
            cin.clear();
            cin.ignore(132, '\n');
        }
        while(choice != 1 && choice != 2 && choice != 3 && choice != 4) {
            cerr << "Invalid Input!!Try again\n" << endl;
            break;
         }
    } while(choice != 1 && choice != 2 && choice != 3 && choice != 4);

這是一個簡短的示例程序,可以確保 ASCII 輸入介於 1 和 4 之間。

#include <exception>
#include <iostream>
#include <string>

int menu_selection() {
  int choice = 0;
  std::string input;

  do {
    std::cout << "\nWhich object would you like to measure:\n"
              << "1. Table\n"
              << "2. Stool\n"
              << "3. Bookshelf\n"
              << "4. Exit\n\n";
    std::getline(std::cin, input);

    // Handles the input of strings
    std::string::size_type loc = 0;
    try {
      choice = std::stoi(input, &loc);
    } catch (std::exception& e) {  // std::stoi throws two exceptions, no need
                                   // to distinguish
      std::cerr << "Invalid input!\n";
      continue;
    }

    // Handles decimal numbers
    if (loc != input.length()) {
      choice = 0;
    }

    // Handles the valid range
    if (choice < 1 || choice > 4) {
      std::cerr << "Invalid Input! Try again\n\n";
    }

  } while (choice < 1 || choice > 4);

  return choice;
}

int main() {
  int selection = menu_selection();

  std::cout << "You chose " << selection << ".\n";
}

此代碼不屬於您的家具類。 選擇家具不是“被”家具。 菜單和選擇應該在課外,然后你對你的家具類進行適當的調用。

另一種思考方式是與其他開發人員共享家具類。 也許他們不關心測量家具。 但是現在您已經通過將其包含在類中來強制對它們進行這種測量。

暫無
暫無

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

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