// Zeinalipour-Yazti Demetrios // csyiazti // cs10xx - Lab Sec#25-#29 // lab6 /* * This program randomly picks a number between 2 and 8 then asks the user * to enter a word that contains that many characters. * It then checks to see if the word entered does indeed have the correct * number of characters and output whether they entered a good word or not. * The programs allows the user to continue as many times as he wants each * time using a different random number. */ #include #include #include #include using namespace std; /* This function returns us a random number in range (from,to) * @return : the random number */ int getRand(int from, int to) { /* e.g (2,4) ==> range=3 [3 numbers] */ int range = to-from+1; // produce random number 0 <= random <= range int random = (rand() % range); // return random number + from in order to scale it up to the range. return ( random + from ); } /* This function asks the user to select the char "y" or "n" * @return : y for yes * n for no */ char doAgain() { /* defining local scope variables*/ char value; cout << "\nDo you want to run the program again (y/n) ?: "; cin >> value; while (cin.fail() || !(value=='y' || value=='n')) { cout << "#Error - only (y/n) are accepted!\n"; cin.clear(); cin.ignore(80, '\n'); cout << "Do you want to run the program again (y/n) ? : "; cin >> value; } cout << endl; return value; } void main() { /* define variables */ int random; /* a random number */ string word; /* defines the type : (1=odd or 2=even) */ /* define functions & procedures*/ char doAgain(); /* returns 'y' or 'n' to the question whether to continue */ int getRand(int from, int to); // produce number : from <= random <= to /* srand -> randomize withou the need for entering a seed each time. * This causes the computer to read its clock to obtain the value for * the seed automatically. * time(0) ==> returns current system time */ srand((unsigned)time(0)); // run the program as many times as the user wants do { // generate random number 2<=random<=8 random = getRand(2,8); cout << "Please enter a word "<< random << " characters long: "; cin >> word; if (word.length()!=random) { cout << "#Error : The given word should be " << random << " chars" << endl; } else { cout << "Congratualtions! - You entered the right number of chars.\n"; } } while (doAgain()=='y'); }