How do I only allow integers and doubles to be input?

I am writing a code that will only allow integers between a minimum and maximum value. I'm having trouble, though, limiting the user to just integers. Here's what I have so far. The commented part is where I'm having trouble.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  int GetInteger(const int& min, const int& max) {
    int input;
    const std::string invalid_int_("Failure: No integer found.");
    const std::string low_int_("Failure: Integer is below minimum value.");
    const std::string high_int_("Failure: Integer is above maximum value.");
    if (/*needs to only accept numbers*/) {
      if (input < min) {
        std::cout << low_int_ << endl;
        input = 0;
      } else if (input > max) {
        std::cout << high_int_ << endl;
        input = 0;
      }
    } else {
      std::cout <<invalid_int_ << endl;
      input = 0;
    }
    return input;
  }


I am also making a nearly identical function, except in this case it would only allow doubles. Can someone please explain to me how to do this? Thank you.

Note: I do not need to accept scientific notation for doubles.
Last edited on
I'm rather new at this, but it looks like, from that code, that they just listed for the input to between two sets of numbers. I suppose I could just require the input to be between two very large numbers, but is there a way to include all numbers? In addition, I'm not sure if this would solve my problem for doubles (unless setting it between 0.0 and 10000.0 would only limit to to doubles or something).
I'm rather new at this, but it looks like, from that code, that they just listed for the input to between two sets of numbers.

The validation is a customization point. You provide whatever criteria you like in the form of a std::function.

If you wanted to get input that included any valid double:

1
2
double value = get<double>("Enter a floating point number: ",
                           [](const double&) { return true; });
Last edited on
Could you explain how this works? In a way, I do need to allow the user to put in non-integers (I just can't accept them). Is there a way I could allow them to input a non-integer with this method and tell them that it is invalid when they do?
Have you tried running the code? (Or looking at the output in the linked post?)

That is exactly what it does.
That's why I'm asking. On the right it seems like the code won't let the user put in anything other than an integer. It keeps making them try again until the user finally cooperates. In this case, I'm supposed to accept non-integers, but tell them it's invalid.
What would you do after you've accepted your invalid input and told the user it was invalid?
Topic archived. No new replies allowed.