Runtime error #2 Yahtzee program

I am in the process of writing a little Yahtzee program out of boredom. However, I have stumbled upon a little error that I cannot seem to solve. I used an integer array to hold the values of six dice. After displaying the values once, then changing some of those values, then displaying again results in the following error:

Debug Error!

Program: ... Studio 2008\Projects\Yahtzee\Debug\Yahtzee.exe
Module: ... Studio 2008\Projects\Yahtzee\Debug\Yahtzee.exe
File:

Run-Time Check Failure #2 - Stack around the variable 'dice' was corrupted.

Here is the code so far for the roll function:
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
int roll{
	int dice[5];
	string keeps;
	cout << "Your rolls are:" << endl;
	for(int i = 0; i <= 5; i++){
		dice[i] = rand()%6+1;
	}
	cout << dice[0] << ' ' << dice[1] << ' ' << dice[2] << ' ' << dice[3] << ' ' << dice[4] << endl;
	cout << "Whice dice would you like to keep?\nEx. 10010 for first and fourth dice." << endl;
	while(true){
		cin >> keeps;
		bool flag = false;
		for(int i = 0; i < keeps.size(); i++)
			if(keeps[i] < '0' || keeps[i] > '1'){
				flag = true;
				break;
			}
		if(!flag)
			break;
		cout << "Invalid. Enter 5 numbers 1 or 0 (1 if you want to keep)." << endl;
	}
	for(int i = 0; i < 5; i++)
		if(keeps[i] != '1')
			dice[i] = rand()%6+1;
	cout << "Your rolls are: " << endl;
	cout << dice[0] << ' ' << dice[1] << ' ' << dice[2] << ' ' << dice[3] << ' ' << dice[4] << endl;
	return 0;
}

I've never seen an error like this before, any help would be appreciated.
When you first fill the dice array with random rolls, your for loop should use i < 5, not i <= 5.
Ironically, you have that set up properly in your second loop that conditionally rerolls.
Make sure to always call cin.ignore(); after using a "cin >>" command.

When you first fill the dice array with random rolls, your for loop should use i < 5, not i <= 5.
Ironically, you have that set up properly in your second loop that conditionally rerolls.

Haha, stupid logical error.

Make sure to always call cin.ignore(); after using a "cin >>" command.

What exactly does that do? In both my C++ classes we never learned to do that.
Matt23488 wrote:
What exactly does that do? In both my C++ classes we never learned to do that.


This will ignore the trailing '\n' that is present if you use >> with std::cin and the user hits enter (assuming there is one, otherwise it will ignore 1 character).

I would suggest used std::getline() instead, which will get an entire line up to the first '\n' for you, which you can then parse yourself.
Ok, I've used std::getline() before, when trying to get strings as input when they have spaces in them...
Topic archived. No new replies allowed.