I need to take in the value of the number of vertices a shape has and I'm taking this as user input. As this number is later being used to create an array, the variable type is int.
However, I've found when troubleshooting that if I don't put in an integer, e.g. 0.1, then the code enters an infinite loop despite me using .clear() and resetting the value of the variable. The code I am using is below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main(){
int vert{0};
//Take in value for the number of vertices
cout << "Please enter the number of vertices of the shape you wish" << endl
<< "to create." << endl;
while (!(cin >> vert) || vert < 3){
//If an illegal value, e.g. a letter, has been entered, display a message and end the code
if (cin.fail()){
cin.clear();
vert = 0;
}
// If the conditions of the while loop are not met, clear the input and display
// a message asking for the correct type of input
cin.clear();
cout << "Please enter an integer greater than or equal to 3." << endl;
}
}
How can I clear cin and the variable so that this infinite loop doesn't occur. I can't use exit/return 0 as I need to take a proper input.