Dice Roller Segmentation Fault

Good day/night, wherever you are,

My friends commissioned me to create a virtual set of dice for their Dungeons & Dragons game. I wrote the C++ program below, which was meant to take in the command line:
#d### [+ * [/2]]


Where the #s to the right of the 'd' indicate how many sides the die has, the # to the left of the 'd' indicates how many times to roll it (summing the results), and the * indicates a number to add to the final result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <cstdlib>
#include <sstream>

int main(int argc, char* argv[])
{
	std::vector<std::string> input;	
	std::stringstream convert;
	int tempi = 0;
	int result = 0;
	
	if (argc < 2)
		return 0;
	
	for (int i = 1; i < argc; ++i)
		input.push_back(argv[i]);
		
	for (int i = 0; i < argc; ++i)
		std::cout << input[i] << ' ';
	
	std::cout << '\n';
	
			int upper = 20, repeat = input[0][0] - 48, othtemp;
			tempi = 0;
			if (input[0].find("d") == 1)
			{	
					convert << input[0].substr(2,3);
					convert >> upper;
						
					for(int j = 0; j < repeat; ++j)
					{
						othtemp = 1 + rand() % upper;
						std::cout << "Roll " << j+1 << " of " << repeat << " (d" << upper << "): " << othtemp << '\n';
						tempi += othtemp;
					}
			}
			else
			{
				convert << input[0];
				convert >> tempi;
			}
			result += tempi;
			if (input.size() >= 3)
			{
				othtemp = 0;
				std::stringstream convert2;
				convert2 << input[2];
				convert2 >> othtemp;
				std::cout << "...Plus " << othtemp << "...\n";
			if (input[1] == "-")
					result -= othtemp;
				else
					result += othtemp;
			}
			if (input.size() == 4 &&input[3] == "/2")
			{
				std::cout << result << "\n";
				std::cout << "Halved...\n";
				result /= 2;
			}
			std::cout << result << '\n';
	return 0;
}
albatrossia-II:Debug jparrot$ ./dndice 1d20 + 2
Segmentation fault


However, since this is an application that takes its input from the command-line, I've had some difficulties debugging it with gdb and determining where the segmentation fault occurs. If any experts could shed some light on this issue, that would be much appreciated.

-Jean Parrot
In gdb, you can just say

"run 1d20 + 2"

and it will pass parameters to your executable.
But your problem is here:

1
2
3
4
5
	for (int i = 1; i < argc; ++i)
		input.push_back(argv[i]);
		
	for (int i = 0; i < argc; ++i)
		std::cout << input[i] << ' ';


second loop iterates one more time than the first.

Iterators!!!
Hmm...

I was curious what an ideal Q/A thread would look like. So I wrote up a short program, threw in an error, and then tried to follow the "How to Ask..." article as closely as possible. Interesting results. :)

Thank you for participating!

-Albatross
Topic archived. No new replies allowed.