Skip to content

Instantly share code, notes, and snippets.

@KronicDeth
Forked from StabbyMcDuck/gist:fa14ba9119e27854292f
Last active August 29, 2015 14:04
Show Gist options
  • Save KronicDeth/d472ef523cac048e2e70 to your computer and use it in GitHub Desktop.
Save KronicDeth/d472ef523cac048e2e70 to your computer and use it in GitHub Desktop.
#include <iostream> // includes and statements section
#include <string> // strings
#include <cstdlib> // c standard library
#include <ctime> // time
using std::cin; // user input
using std::cout; // machine output
using std::endl; // for line breaks
using std::strtol; // convert string to int
using std::string; //string
using std::getline; //getline
/**
* Return whether the given `inputMaximum` contains a whole number (an integer >= 0).
*
* @return [true] if all characters are in '0' to '9'
* @return [false] otherwise
* @see http://stackoverflow.com/a/1885793/470451
**/
bool wholeNumber(const string& input){
bool notAnInteger = false;
for (int i = 0; i < input.length(); i++) {
if (!(input.at(i) >= '0' && input.at(i) <= '9')) {
cout << "Your number is not a whole number!" << endl;
notAnInteger = true;
break;
}
}
return notAnInteger;
}
int main () {
string inputMinimum;
string inputMaximum;
int minimum;
int maximum;
// use a do while loop because you want it to run at least once.
do {
// have to ensure 0 or while loop may fail to continue on flip due to random
// initialization
minimum = 0;
maximum = 0;
cout << "RANDOM NUMBER GENERATOR!" << endl;
cout << "Please enter a minimum whole number for our range: " << endl;
getline(cin, inputMinimum);
bool notAnInteger = false;
notAnInteger = wholeNumber(inputMinimum);
if (notAnInteger) {
continue;
}
// convert string to integer now that we know nothing will get cut off
minimum = atoi(inputMinimum.c_str());
cout << "Now please enter a maximum whole number for our range: " <<endl;
getline(cin, inputMaximum);
notAnInteger = wholeNumber(inputMaximum);
}
if (notAnInteger) {
continue;
}
// convert string to integer now that we know nothing will get cut off
maximum = atoi(inputMaximum.c_str());
if (minimum >= maximum)
{
cout << "I'm sorry, your minimum is greater than or equal to your maximum. Please try again!" << endl;
}
}
while (minimum >= maximum);
// seed the random number generator
srand(time(NULL)); // Used 'NULL' instead of 0, defined as null pointer in http://www.cplusplus.com/reference/ctime/time/?kw=time
int range = maximum - minimum + 1;
int randomInRange = minimum + rand() % range;
cout << "Your random number is: " << randomInRange << endl ;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment