I am trying to ensure that the user inputs only int
types to my program.
The code is below:
// Use namespace std to avoid needing to write things like std::cout
using namespace std;
// Include iostream for input / output interfacing
#include <iostream>
// Needed for error checking if inputs are actually ints
#include <cstdlib>
// Main function
int main(){
// Introduction + instruction to input data
cout << "Hello and welcome to Jerry's Triangle Test. " << endl << "Please submit three integers that represent the lengths of a triangle: \n";
// Declare fundamental int types for user input
int first_int, second_int, third_int;
// Take in the three user inputs
cin >> first_int;
cin >> second_int;
cin >> third_int;
// Check to see if cin has taken in anything other than an int
if (cin.fail()){
// If it has, error the program out and return 1 to exit
cout << "ERROR - Value was not an INTEGER. Please retry using an INTEGER.";
return 1;
// Otherwise, continue on
}else{
// Report back what the inputs were
cout << "\nYour first integer was: " << first_int;
cout << "\nYour second integer was: " << second_int;
cout << "\nYour third integer was: " << third_int;
// Perform logic to check what kind of triangle it must be from the entered dimensions.
// If all three ints are equal, it is equilateral.
if (first_int == second_int && second_int == third_int){
cout << "\nEQUILATERAL";
// If only two are equal, its isosceles.
} else if (first_int == second_int || first_int == third_int || second_int == third_int){
cout <<"\nISOSCELES";
// If neither of those conditions are true, then none must match, so it is scalene.
} else{
cout <<"\nSCALENE";
}
// Return 0 for a successful program.
return 0;
}
}
Entering 1,1,1
works as expected.
However, entering: 1, 1, 0.2
yields ISOSCELES
, when it should error out. Why does cin.fail()
not notice that is incorrect?
But, if I enter 0.2
first or second, the program properly terminates.
I would hope that if the user enters a float ANYWHERE, the program errors out with "ERROR - Value was not an INTEGER. Please try using an INTEGER"
(It would be great to test each input individually to determine which was problematic, but I could not determine how to do that)
How can I correct my current codes to account for something as I am describing?