Home >Backend Development >C++ >How Can C Streams Be Used to Reliably Handle Invalid Numeric Input?
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:
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!