简体   繁体   中英

Validating Integer Input in C++

I am trying to validate input, to accept only integers, and its working fine for letters and decimal points after 4. For example if I enter 1.22 it will read number one only and go to infinitive loop, but when I enter number what are bigger than 4, for example 5.55 it is working good then, how can I solve this problem? Thank you and appreciate your help!

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);

Here's a short example program that can ensure an ASCII input is between 1 and 4 inclusive.

#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";
}

This code does not belong in your Furniture class. Choosing furniture is not "being" furniture. The menu and selection should be outside the class, and then you make the appropriate calls to your Furniture class.

Another way of thinking about this is sharing the Furniture class with other devs. Maybe they don't care about measuring furniture. But now you've forced this measurement on them by including it in the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM