Home >Backend Development >C++ >How to Make `cin` Accept Only Numerical Input in C ?
Making cin Read Only Numbers
Enforcing numerical input using cin can present challenges, especially when handling mixed input types. This article investigates a solution to ensure that cin accepts only numerical values.
In the provided code, while loops attempt to rectify invalid input by disregarding non-numerical characters. However, this method faces limitations when dealing with multiple inputs.
Solution: Using std::getline and std::string
To overcome this hurdle, we can employ a more comprehensive approach:
Convert the string to a double using std::stringstream:
Validate the conversion:
Here's an example implementation:
#include <sstream> #include <string> 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; }
This solution ensures that both integers and floating-point numbers are processed correctly, with non-numerical characters being discarded completely.
The above is the detailed content of How to Make `cin` Accept Only Numerical Input in C ?. For more information, please follow other related articles on the PHP Chinese website!