Home > Backend Development > C++ > How to Prevent Infinite Loops Caused by Invalid Input with `cin`?

How to Prevent Infinite Loops Caused by Invalid Input with `cin`?

Susan Sarandon
Release: 2024-12-31 14:48:12
Original
502 people have browsed it

How to Prevent Infinite Loops Caused by Invalid Input with `cin`?

Infinite Loop with Invalid Input and cin

When using cin to read input, an infinite loop can occur if the input is not of the expected type. This issue is particularly apparent when attempting to input numbers but accidentally entering characters.

The problem stems from the fail state that cin enters when it encounters invalid input. In such scenarios, cin will不再 prompt for input, resulting in an infinite loop.

To prevent this behavior, one solution is to check if cin is in the fail state. If it is, the fail state is cleared, and the bad input is discarded using cin.ignore(). This allows cin to return to its normal operation and prompt for further input.

if (cin.fail()) {
  cout << "ERROR -- Invalid input detected" << endl;
  cin.clear();
  cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Copy after login

Alternatively, you can use std::getline() to read the input as a string and perform more sophisticated validation checks before trying to convert it to a number. This approach provides greater flexibility and allows for more complex input validation.

The above is the detailed content of How to Prevent Infinite Loops Caused by Invalid Input with `cin`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template