do {
cout<<"How many: ";
cin.get();
cin>>num;
cin.ignore();
}while ((num<1)||(num>3));
The problem is if I input something "djkhgf", it stucks in a infinity loop. Can someone tell me what is the problem or how can i control the user's input between 1-3 ?
It's going into an infinite loop because an iostream turns into a zombie object on error. Use cin.clear() every iteration, or use the better-designed, faster stdio.h library.
there is already a cin.clear() line in the loop. but still infinite loop occurs if i input "ldkfg" etc... any other ideas? or what is this "faster stdio.h lib" ? any example pls?
whocares21, the reason your code still goes into infinite loop is that if cin>>num; fails the it goes into error state so cin.ignore(); will do nothing. cin.clear(); clears the error state.cin>>num; reads the same input again and of course fails again. And there you have an infinite loop.