Putting data into an array

closed account (zbREy60M)
Hello,

I'm trying to write a program that generates a series of random coordinates. Right now, I've only gotten to the part where I am generating one random number. I can cout this so that I can see the number, but when I use myfile to output it into a .txt file I only get the first data point. This makes me think that I need to put the data into an array and then output that. The problem is that I can't figure out how to put these numbers into an array. In the "while" loop I keep getting errors like "cannot allocate an array of constant size 0" and "cannot convert from double to double[]", can anyone help me with this? Thanks!

*As an added note if I change the array called radius into just a double, and then have it cout radius 'm' times, then it works just fine and I get 'm' random numbers. However if I declare radius to be an array of size 'i' then i get an error. If I declare it to be of size 'm' then I just get the same random number 'm' times.

int main()
{
int i = 0;
double normalization = rand() % 32000;
seed();
int m ;
cout << "How many gravitars?\n\n";
cin >> m;

while (i < m)
{

double radius[i] = unifRand()*(normalization);
i++;
cout << radius[i] << endl;
}
system("PAUSE");
return 0;
}
Last edited on
double radius[i] = unifRand()*(normalization);

You can't declare an array like this.

Really, radius doesn't need to be an array, just make it a normal var:

1
2
3
double radius = unifRand()*(normalization);  // get rid of the [i]
i++;
cout << radius << endl;  // here too 



EDIT:

or, if you need it to be an array, you'll have to declare the array outside the loop and give it the total size (in this case, that's 'm'):

1
2
3
4
5
6
7
8
double* radius = new double[m];
for(i = 0; i < m; ++i)
{
  radius[i] = blah;
  cout << radius[i] << endl;
}

delete[] radius;  // don't forget to delete[] stuff that you new[]'d 


Also note you shouldn't increment i before printing radius[i] or you will be printing the wrong radius. I changed it to a for loop here to correct that problem and also because it's more "normal" and intuitive for this kind of loop.
Last edited on
closed account (zbREy60M)
This is similar to how I had it before, in which it worked fine and if I entered '50' then it would cout 50 random numbers, which is exactly what I need. However, when I went to export them to text file, I would only get the first number. How would I go about exporting ALL the data to a txt file? I was just assuming I would need an array to do that.
Topic archived. No new replies allowed.