Skip to content

Instantly share code, notes, and snippets.

@StabbyMcDuck
Created July 18, 2014 23:58
Show Gist options
  • Save StabbyMcDuck/fa14ba9119e27854292f to your computer and use it in GitHub Desktop.
Save StabbyMcDuck/fa14ba9119e27854292f 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
int wholeNumber(){
bool notAnInteger = false
for (int i = 0; i < inputMaximum.length(); i++) {
if (!(inputMaximum.at(i) >= '0' && inputMaximum.at(i) <= '9')) {
cout << "Your number is not a whole number!" << endl;
notAnInteger = true;
break;
}
}
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;
wholeNumber;
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);
wholeNumber;
}
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