c++ – Cycle crash?

Question:

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 get an error.

I had done this, but I noticed that after a certain number of figures, the program ending 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");
}

Answer:

but I noticed that after a certain number of figures, the program ending up throwing only the error line.

You are storing the numbers in b , which is of type int . The int type 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 not be able to store it in the variable and this causes an error flag to be set … from then on cin is blocked until you deal with the error.

The most common in these cases is to clear the error flag and empty the input buffer:

while (b > 9999 || b < 1110) {
    std::cout << "\nE R R O R. Favor de ingresar un numero de cuatro digitos.\n";
    std::cin >> b;
    if( std::cin.fail() )
    {
      std::cin.ignore(std::numeric_limits<int>::max(),'\n');
      std::cin.clear();
    }
}

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 type int . numeric_limits is in the limits library.
  • 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 numeric_limits is used … we want to discard as much as possible.
  • cin.clear resets the error flag, which makes cin again available to read new values.

EDIT

The problem with the previous answer is that it does not cover the case of incorrect input being entered in the first iteration. I don't like repeating code, so a possible solution would be the following:

int main()
{
    int b;
    bool pedirNumero = true;
    while(pedirNumero)
    {
        std::cin >> b;
        pedirNumero = std::cin.fail() || b > 9999 || b < 1110;

        if( pedirNumero )
        {
          std::cout << "\nE R R O R. Favor de ingresar un numero de cuatro digitos.\n";
          std::cin.ignore(std::numeric_limits<int>::max(),'\n');
          std::cin.clear();
        }
    }
    std::cout << b;
}
Scroll to Top