I am sure I am missing on a very simple thing here. My code looks something like this. It just checks what is the type of triangle.
try { double FirstSide,SecondSide,ThirdSide; cout<<"Enter the first side: "; cin>>FirstSide; if(cin.fail()) { throw invalid_argument("Your input doesn't look to be a number."); } if(FirstSide > numeric_limits<double>::max() || FirstSide<0) { throw invalid_argument("Input is out of range."); } cin.ignore(); // Used afterwards, just to check cout<<"Enter the second side: "; cin>>SecondSide; if(cin.fail()) { throw invalid_argument("Your input doesn't look to be a number."); } if(SecondSide > numeric_limits<double>::max() || SecondSide<0 ) { throw invalid_argument("Input is out of range."); } cout<<"Enter the third side: "; cin>>ThirdSide; if(cin.fail()) { throw invalid_argument("Your input doesn't look to be a number."); } if(ThirdSide > numeric_limits<double>::max() || ThirdSide < 0) { throw invalid_argument("Input is out of range."); } // Check for equilateral if(FirstSide == SecondSide == ThirdSide) { cout<<"The triangle is equilateral. "; } else if(FirstSide == SecondSide || SecondSide == ThirdSide || FirstSide == ThirdSide) { cout<<"The triangle is isosceles."; } else { cout<<"The triangle is scalene. "; } } catch(invalid_argument& error) { cerr<<error.what()<<" Will now exit. "<<endl; return -1; } If I input 2p, I get the output: Enter the second side: Your input doesn't look to be a number. Will now exit.
Since the input is invalid for FirstSide, Enter second side: should not actually be printed. I am aware of the fact that compiler might be taking 2 for FirstSide and trying to assign p to SecondSide and hence the behaviour. If I ignore the values in stream (by using cin.ignore(), I actually get no error).
My question is how do I get my input correct for such cases like 2p or 1k?
Thanks.
EDIT:
Another question has popped up from the comments, How is the FirstNumber > numeric_limits<int>::max() comparison actually working if the value has already been assigned to FirstNumber ? Reference: https://msdn.microsoft.com/en-IN/library/hh279678.aspx
SecondSide > numeric_limits<int>::max()makes sense. Once the value is assigned to aint, it can only be< = numeric_limits<int>::max()and the comparison will always return true.cins are also fixed, so there is no need to include it in an mcve.