So I'm writing a program that simulates a dice roll based on an input given by the user in XdY format where X = the number of dice to be rolled and Y = the number of sides on the dice.
I haven't worked on option 2 (an option that computes the specified XdY roll multiple times) because I have an error with option 1. Every time I enter something in in the proper format, instead of giving me an expected roll number, it gives me some huge number in the 30000s.
#include <iostream>
#include <ctime>
#include <sstream>
#include <string>
usingnamespace std;
constint OPTION_SINGLE_ROLL = 1;
constint OPTION_MULTI_ROLL = 2;
constint OPTION_QUIT = 3;
int simulate_dice_roll (int& x, int& y) { // simulates dice roll based on XdY input
int result;
for (int i = 0; i < x; i++) {
result += rand() % y;
result++;
}
return result;
}
int extract_x (string dice_info_xdy) { // extracts X value from XdY string input
stringstream ss;
ss << dice_info_xdy.substr(0, dice_info_xdy.find("d"));
int x;
ss >> x;
return x;
}
int extract_y (string dice_info_xdy) { // extracts Y value from XdY string input
stringstream ss;
ss << dice_info_xdy.substr(dice_info_xdy.find("d") + 1);
int y;
ss >> y;
return y;
}
int main() {
srand(time(NULL));
bool return_to_root_menu;
bool return_to_option_1;
do {
cout << "\t\t\t***ROOT MENU***\nPlease select one of the following options:\n1 - Simulate a single dice roll\n2 - Simulate multiple dice rolls\n3 - Quit the program\n";
int option_choice;
cin >> option_choice;
cin.fail(); { // resets to root menu if a character or string is input instead of an int
cin.clear();
cin.ignore(1000, '\n');
}
if (option_choice == OPTION_SINGLE_ROLL){
do {
cout << "\nPlease enter information of roll in XdY format: ";
string dice_info_xdy;
cin >> dice_info_xdy;
int x, y;
x = extract_x(dice_info_xdy);
y = extract_y(dice_info_xdy);
if (x < 1 || y < 1 || dice_info_xdy.find("d") == -1) { // resets option 1 if input is
cout << "Invalid input."; // invalid
continue;
}
int result = simulate_dice_roll(x, y);
cout << "Result: " << result << endl; // displays result of dice roll
return_to_option_1 = true;
} while (return_to_option_1 == false);
}
if (option_choice == OPTION_QUIT) {
cout << "Goodbye!";
return_to_root_menu = true;
continue;
}
return_to_root_menu = false; // resets to root menu when program is finished
continue;
return 0;
} while (return_to_root_menu == false);
}
Set a breakpoint and step through each line of code, keeping an eye on the contents of each variable so that you can make sure the contents are what you expect. If they're not, you know where the problem is.
Debuggers really should be taught from day 1. People should be using them before they write their first line of code. There's no better way to illustrate how program flow works than seeing it in action.