1
0

Compare commits

..

3 Commits

Author SHA1 Message Date
18c5f972c2
T1 Q3 2022-10-07 12:35:44 +01:00
a7efeab624
T1 Q2 2022-10-07 12:18:23 +01:00
3d2827578e
Tutorial 1.
Question 1.
2022-10-07 12:10:31 +01:00

115
main.cpp
View File

@ -1,101 +1,30 @@
#include <iostream> #include <iostream>
#include <random> #include <cstdlib>
#include <chrono> #include <ctime>
using string = std::string;
void ignoreTillLineEnd();
string promptfs(string);
int promptfi(string);
string guessRank(int);
int main() int main()
{ {
std::mt19937 rand {std::random_device{}()}; using std::cout;
std::uniform_int_distribution<int> clamp {1, 100}; using std::cin;
string name {promptfs("Enter your name:")}; srand(time(nullptr));
std::cout << "Hello " << name << ", welcome to guess the number.\n"; int gcount{ 1 };
int guesses {}; int n { 20 };
int num {clamp(rand)}, ent {}; int secret { rand()%n + 1 };
do { cout << "Guess a number between 1 and " << n << ": ";
if (guesses++ > 0) { int guess;
if (ent > num) cin >> guess;
std::cout << "You Guessed Too High!\n"; while (guess != secret)
else {
std::cout << "You Guessed Too Low!\n"; if (guess > secret) {
cout << "Number too big ; ";
} else {
cout << "Number too small ; ";
} }
ent = promptfi("Enter your guess:"); gcount++;
cout << "Guess again: ";
cin >> guess;
} }
while (num != ent); cout << "Correct!\n";
std::cout << "Well done " << name << ", you guessed correctly!\n"; cout << "Took " << gcount << " tries.\n";
std::cout << "You took " << guesses << " guesses, rank " << guessRank(guesses) << " .\n";
return 0; return 0;
} }
void ignoreTillLineEnd() {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
string promptfs(string msg) {
bool once {};
string toret {};
do {
if (once) {
std::cin.clear();
ignoreTillLineEnd();
std::cout << "Input Failure!\n";
}
std::cout << msg << "\n";
std::cin >> toret;
once = true;
}
while (std::cin.fail());
ignoreTillLineEnd();
return toret;
}
int promptfi(string msg) {
bool once {};
int toret {};
do {
if (once) {
std::cin.clear();
ignoreTillLineEnd();
std::cout << "Input Failure!\n";
}
std::cout << msg << "\n";
std::cin >> toret;
once = true;
}
while (std::cin.fail());
ignoreTillLineEnd();
return toret;
}
string guessRank(int g) {
switch (g) {
case 0:
return "U";
case 1:
return "A^";
case 2:
return "A*";
case 3:
return "A";
case 4:
case 5:
return "B";
case 6:
case 7:
return "C";
case 8:
case 9:
case 10:
return "D";
case 11:
case 12:
case 13:
return "E";
default:
return "F";
}
}