Home > Backend Development > C++ > How to Ensure Valid Double Input in C ?

How to Ensure Valid Double Input in C ?

Linda Hamilton
Release: 2024-12-01 06:02:11
Original
657 people have browsed it

How to Ensure Valid Double Input in C  ?

How to Validate User Input as a Double in C

When working with user input, validating it is crucial to prevent erroneous data from being processed. One common issue is ensuring that the entered value is a valid double. Here's how to address this issue in C .

The provided code checks if the user input is a valid number using cin >> x. However, if the input is not a double, it infinitely outputs the "Invalid Input!" statement. To rectify this, implement a loop that continuously prompts for input until a valid double is entered.

while (true) {
  if (cin >> x) {
    // Valid number
    break;
  } else {
    // Not a valid number
    cout << "Invalid Input! Please input a numerical value." << endl;
    cin.clear(); // Clear the error state
    while (cin.get() != '\n') ; // Empty loop to discard the line
  }
}
Copy after login

This modified code first checks if the input is a valid number. If not, it outputs the error message and clears the error state, then reads and discards everything that was entered on the previous line. This ensures that the user is prompted to enter a valid double and the program doesn't get stuck in an infinite loop of error messages.

The above is the detailed content of How to Ensure Valid Double Input in C ?. 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