I have a problem with a while loop. I want my program to only accept 4-digit numbers, and if the user enters one outside the range, it will throw an error.
I had done this, but I noticed that after a certain number of figures, the program ended up throwing only the error line. I would like to know what I am doing wrong.
#include iostream
int main()
{
int a=1, b;
std::cin >> b;
while (b > 9999 || b < 1110) {
std::cout << "\nE R R O R. Favor de ingresar un numero de cuatro digitos.\n";
std::cin >> b;
}
std::cout << b;
system("pause");
}
You are storing the numbers in
b
, which is of typeint
. The typeint
is a signed integer data type. This 32-bit data type uses one bit to store the sign and the remaining 31 to store the number itself.That is, for 31 bits, the largest number it can support is: 2^31-1 = 2,147,483,647.
If you try to enter a larger number,
cin
it won't be able to store it in the variable and this causes an error flag to be set... from then oncin
it blocks until you deal with the error.The most common in these cases is to clear the error flag and empty the input buffer:
Where:
numeric_limits
is a C++ template that gives you information about numeric types. In this case we are asking for the highest value that can be stored in a variable of typeint
.numeric_limits
It is in the bookstorelimits
.cin.ignore
discards input characters... in this case it will discard everything until it encounters a newline (which will also be discarded). The first parameter indicates the number of bytes to discard... hence it is usednumeric_limits
... we want to discard as many as possible.cin.clear
resets the error flag, which makes itcin
available again to read new values.EDIT
The problem with the previous answer is that it doesn't cover the case of wrong input being entered on the first iteration. I don't like to repeat code, so a possible solution would be the following:
I would suggest a change of strategy. Instead of capturing numbers it captures strings (the length limit of character strings is as long as the computer's memory allows). With character strings you will have no limit to the length of the input numbers.
Once the string is captured, you can check if it is of length 4 and if it is made up of numbers:
The function
std::all_of
checks that all the elements between the supplied iterators meet a condition, in this case we check that they are all numbers withstd::isdigit
, which it returns0
when the supplied character is not a digit.You can see the code working in Wandbox 三へ( へ՞ਊ ՞)へ ハッハッ.