I'm new on C++ programming and I tried to write a program to randomly generate some numbers as "Dice Roller". I requested the user to insert the limit of the roll by "cin", and the program works fine, but when the input is anything else that "short int", the program gets out of control and repeats itself. Here is the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
usingnamespace std;
int main () {
short limit, roll;
srand ( time (NULL) );
while (intconst repeat = 100) {
cout << "Enter the maximum limit: ";
cin >> limit;
//Error handling
if (cin.fail() || !isspace(cin.get())){ // If the reading operation stopped on unusual character (not space)
// To prevent such input as '123abc'
cout << "Please enter an integer." << endl << endl;
cin.clear();
while(!isspace(cin.get())); // Throw all useless characters from this input
continue;}
elseif (limit <= 0) {
cout << "Please enter a number greater than \"0\"" << endl;
continue;}
roll = rand()%limit+1;
cout << "You have rolled: " << roll << ". Limit: " << limit << "." << endl << endl << endl;}
return 0;
}
Thank you for the solution. Now the program displays the "Please enter an integer." message and continues the loop instead of repeating itself and getting out of control. As a novice, I couldn't fully comprehend the logic of how the fix codes detect the wrong type of input and throw it, and I'm going to do research on them.