Number Guessing game
C++ Primer - up to Chapter 6
Number guessing game
Range minimum maximum
78 - player guess
How to respond:
Higher!
Lower,
Correct
97 lower
89 lower
85 higher
88 correct!
|
\/
finish
|
\/
Do you want to play again!
Pseudocode
main
define variables
while loop
...
Include string
Function
moodle: 25 February - 3 March
#include
#include
int main() {
int minValue{1};
int maxValue{100};
return 0;
}
...
Pseudocode
include string
main
min and max
user input
prompt for input
Accept input
Code
#include
#include
using std::cin;
using std::cout;
int main() {
int minValue{ 1 };
int maxValue{ 100 };
string input{ cin };
cout << “Input a number: “;
cin >> input;
}
...
std::cin >> minValue >> maxValue;
C++ Primer - Chapter 17
Section 17.4
Default Random Engine
default_random_engine e;
cout << e() << endl;
std::uniform_int_distribution intValue(1, 100);
cout << intValue(e) << endl;
complete code here:
#include
#include
using std::cin;
using std::cout;
int main() {
int minValue{ 1 };
int maxValue{ 100 };
string input{ cin };
cout << “Input a number: “;
cin >> input;
default_random_engine e;
cout << e() << endl;
std::uniform_int_distribution intValue(1, 100);
cout << intValue(e) << endl;
}
...
int theNumber = intValue(e);
cout << intValue(e) << endl;
cout << “Choose a number between “ << minValue << “ and “ << maxValue << “ : “;
int guessNumber{ 0 };
cin >> guessNumber
if (guessNumber > theNumber)
cout << “My Number is lower than: “ << guessNumber << endl;
else if (guessNumber < theNumber)
cout << “My Number is higher than “ << guessNumber << endl;
else
cout << “You've won!” << endl;
while loop or do while loop.
Do While loop
do {
.
.
} while()
A seed is required.
System time?
How to seed
Check if input numbers are correct
Ask if you want to play again.
How to sed
Use system time.
...
Conditions
1 - In between the minimum and maximum
2 - A number
What to do if either of those aren't met.
Cin >> guessNumber
if (guessNumber > minValue && guessNumber < maxValue)
...
cin guessNumber;
try {
cin << guessNumber
} catch (runtime error e) {
“Please enter a number”
}
Try Catch
using std::getline;
int main() {
string sInput:
getline(std::cin >> sInput);
int anIntValue{ 0 };
return 0;
}
string gradeResult (int gradeValue) {
string sReturnValue{ “” };
if (gradeValue > 90)
sReturnValue = “A”;
else if (gradeValue > 80)
sReturnValue = “B”;
else if (gradeValue > 70)
sReturnValue = “C”;
else if (gradeValue > 60)
sReturnValue = “D”;
else
sReturnValue = “F”;
return sReturnValue;
}
int nIntValue{ 0 };
cout << gradeResult(stoi(sInput)) << endl;
Between string and main - swap function
int swap(int a, int b) {
int netVal;
int temp;
temp = a;
a = b;
b = temp;
cout << “A: ” << a << “B: ” << b << endl;
return retVal;
}
int a{ 10 };
int b{ 20 };
swap(a, b);