T
T
Test Test2014-11-19 00:06:07
Programming
Test Test, 2014-11-19 00:06:07

Why does a C++ program loop?

Good evening! Such a problem. I am writing a program (homework). It is required to get the parameter and check it for any conditions.
Piece of the program:

int checked = 0;
int n;
      
      while (checked <= 0) {
        cout << "Введите параметр N=";
        cin >> n;
        
        cout << n;
        
        if ((int)n == 0) {
          cout << "Ошибка! Параметр N не должен равняться 0" << endl;
        } else {
          checked = 1;
        }
        

      }

1. When you enter 1 - good
2. When you enter 0 - it displays an error, and asks you to enter data again (good)
3. When you enter 0.1 - it displays an error, and looping occurs
Do not tell me how to solve the problem, or is there an alternative solution to this problem ? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ruchkin, 2014-11-19
@cubooks

In order to understand why this happens, I will add:
When trying to read 0.1, only 0 is read, since an integer is required, and ".1" remains in the stream. Accordingly, the second time there is an attempt to read an integer from ".1", which leads to an error, and std::cin comes into an erroneous state (std::ios::failbit), n remains unchanged, and everything starts to go in a circle.
Changing it to double only fixed that, but type "0.1blabla" and it will loop again.
Solution:
1. Check std::cin for validity if (std::cin) and, for example, exit or restore the state:

if (!std::cin)
{
  std::cin.clear(); // очищаем флаги
  std::cin.ignore(INT_MAX, '\n'); // игнорим входной буфер до переноса строки
}
// можем пользоваться

2. In addition, you can ask the thread to throw exceptions on errors, for example:
Throws an exception on an unsuccessful attempt to read the value.
In your case, I think it's worth checking std::cin, ignoring the rest of the input, and restoring the state.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question