c++ - How to make cin take only numbers -
here code
double enter_number() { double number; while(1) { cin>>number; if(cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "invalid input " << endl; } else break; cout<<"try again"<<endl; } return number; }
my problem when enter 1x, 1 taken input without noticing character left out run. there way how make work real number e.g. 1.8?
i use std::getline
, std::string
read whole line , break out of loop when can convert entire line double.
#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; }
Comments
Post a Comment