# What's causing this?

This topic is 4760 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm working on a lottery simulator, and it all works fine until I display the random numbers the computer chose. They are 7 random numbers between 1 and 49, and all 7 must be different. That itself works fine until I display them. Here's the function:
void shownumbers()
{

using namespace std;

cout<<"Here are the numbers:  ";

int cloop;  // Counter variable

for(cloop=0;cloop<6;cloop++)
{

cout<<compnums.at(cloop);

cout<<"    ";

}

cout<<"   Bonus Ball:   "<<compnums.at(7);   // Vector element 7 is the Bonus Ball, should be displayed separately at the end

}


The first 6 vector elements display fine, but when the loop exits and cuts to the cout<<" Bonus Ball: " line, it doesn't do it. It says "abnormal termination" and the program exits from there. If I set the loop to go to 7, comment out the dodgy line and display all vector elements without explicitly, on screen, saying element 7 is the Bonus Ball, there is no crash. So what's causing the crash? I'm sure it's something blindingly obvious, but I can't see it. I need a set of fresh eyes to look at this. Thanks, ukdeveloper.

##### Share on other sites
Try changing the 7 to a 6. C/C++ count from 0 not 1.

##### Share on other sites
Quote:
 Original post by mike25025Try changing the 7 to a 6. C/C++ count from 0 not 1.

Quoted for being the answer, which I will expand upon.

If one looks at your loop, you'll notice that you do: cloop < 6. This means that this loop will not execute when cloop == 6. Your loop covers:

"[0..6)" - that is, 0, 1, 2, 3, 4, and 5.

You then skip 6 (which is really ball #7) and go to 7 (which would be ball #8, which dosn't exist)

##### Share on other sites
Yep, stupid n00b mistake of mine.

It was exactly that, I fixed it and all's good now.

Thanks!

• 39
• 15
• 9
• 23
• 10