In C , the cin function can be used to read user input, but it becomes problematic when attempting to validate the input as a valid number. This issue arises when non-numeric characters are input, potentially leaving behind partial input for the next iteration.
One solution is to utilize std::getline and std::string to read the entire line of input. Subsequently, std::stringstream is employed to parse the input and extract a double value. The loop continues until the entire line can be successfully converted to a double, eliminating the issue of leftover input.
#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; }
The above is the detailed content of How to Reliably Input Numbers Using `cin` in C ?. For more information, please follow other related articles on the PHP Chinese website!