How to check if input is numeric in C++ -
i want create program takes in integer input user , terminates when user doesn't enter @ (ie, presses enter). however, i'm having trouble validating input (making sure user inputting integers, not strings. atoi() won't work, since integer inputs can more 1 digit.
what best way of validating input? tried following, i'm not sure how complete it:
char input while( cin>>input != '\n') { //some way check if input valid number while(!inputisnumeric) { cin>>input; } }
when cin
gets input can't use, sets failbit
:
int n; cin >> n; if(!cin) // or if(cin.fail()) { // user didn't input number cin.clear(); // reset failbit cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input // next, request user reinput }
when cin
's failbit
set, use cin.clear()
reset state of stream, cin.ignore()
expunge remaining input, , request user re-input. stream misbehave long failure state set , stream contains bad input.
Comments
Post a Comment