program crashes

im trying to assign underscores into a string randomly but it gives out an error when i run it. im making a hangaroo game,, thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void assign()
{
     int x;
     int len = strlen(ANSWER);
     for(x=0; x<len; x++){
     srand((unsigned)time(&t));
      int y;
      y = rand()%3;
      cout << y;
      if(y == 2){
           tempwordhold[x] = '_';
           }
      }
}
Don't call srand every time you generate a random number like that. You only call srand once when the program starts.

Also, you're not showing us enough. What is ANSWER? What is tempwordhold?

You're probably misusing char arrays. But without seeing what your variables are, it's hard to say.
1
2
char *ANSWER= {"STUDENT"};
*tempwordhold = {"STUDENT"};


sorry, they hold the words i use for the hangaroo game im making, and tempwordhold was meant to be partially replaced by underscores randomly each time i run it. I already tried removing the srand and put it outside the loop but it still crashes
Okay ... you are misusing char arrays.

Until you know more about memory management and exactly what a pointer is, dont' use char arrays to hold strings. (And in fact I wouldn't even do it after you understand all of that unless you have compelling reason to).

Instead, use a string:

1
2
3
4
5
6
7
8
9
#include <string>  // put this with your includes

std::string ANSWER = "STUDENT";  // make these strings instead of char pointers.
std::string tempwordhold = "STUDENT";

//...

//int len = strlen(ANSWER); // boo
int len = ANSWER.length();  // yay 


You might have to change some other things in your program to get it to work with strings, but after you do that you should be good.
Topic archived. No new replies allowed.