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(constint& min, constint& 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;
} elseif (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.
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).
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?
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.