Home >Backend Development >C++ >How Can C Streams Be Used to Reliably Handle Invalid Numeric Input?

How Can C Streams Be Used to Reliably Handle Invalid Numeric Input?

Barbara Streisand
Barbara StreisandOriginal
2024-12-28 15:11:141009browse

How Can C   Streams Be Used to Reliably Handle Invalid Numeric Input?

Resolving Invalid Input with C Streams

Problem:

The provided code aims to prevent non-numeric characters from being accepted as input. However, it fails to handle situations where the input includes a character after a valid number.

Proposed Solution:

To address this issue, we suggest employing a different approach using std::getline and std::string.

Code Snippet:

#include <string>
#include <sstream>

int main() {
    std::string line;
    double d;
    while (std::getline(std::cin, line)) {
        std::stringstream ss(line);
        if (ss >> d) {
            if (ss.eof()) {   // Success
                break;
            }
        }
        std::cout << "Error!" << std::endl;
    }
    std::cout << "Finally: " << d << std::endl;
}

Explanation:

This revised solution follows these steps:

  1. Read the entire line: Using std::getline, the entire line of input, including spaces and special characters, is taken into a string variable line.
  2. Convert the string to double: A std::stringstream object ss is created to hold the string line. The stream is then used to extract the numeric value using the >> operator.
  3. Check for successful conversion: If the ss stream successfully extracts the number and reaches the end of the string, it indicates a valid numeric input.
  4. Handle errors: If the conversion fails, an error message is displayed.
  5. This approach ensures that only valid real numbers are accepted as input, regardless of any trailing characters or spaces in the input.

    The above is the detailed content of How Can C Streams Be Used to Reliably Handle Invalid Numeric Input?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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