Answer the question
In order to leave comments, you need to log in
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;
}
}
Answer the question
In order to leave comments, you need to log in
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'); // игнорим входной буфер до переноса строки
}
// можем пользоваться
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question