首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正在验证C++中的整数输入

正在验证C++中的整数输入
EN

Stack Overflow用户
提问于 2020-03-19 21:31:53
回答 1查看 139关注 0票数 0

我正在尝试验证输入,只接受整数,它对4之后的字母和小数点工作得很好。例如,如果我输入1.22,它将只读取数字1并进入无限循环,但当我输入大于4的数字时,例如5.55,它工作得很好,那么我如何解决这个问题?谢谢并感谢您的帮助!

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-19 21:56:16

下面是一个简短的示例程序,可以确保ASCII输入介于1和4之间(包括1和4)。

代码语言:javascript
复制
#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";
}

此代码不属于您的家具类。选择家具并不是“做”家具。菜单和选择应该在类之外,然后对您的家具类进行适当的调用。

考虑这一点的另一种方式是与其他开发人员共享家具类。也许他们不关心测量家具的尺寸。但现在,您通过将其包含在类中,将此度量强加给了他们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60758281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档