OutPut Array To Txt File

May 27, 2009 at 10:50pm
I have been scrolling around on forum to forum and i have noticed that
many people are lost when comming to outputting an array and dealing with Random Numbers. So ill try my best (still very noobish) at showing you what i know.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <ctime> // needed for rand && srand
using namespace std;

int main()
{
    const int SIZE(100);
    int rand_NUM[SIZE]; 

    srand((unsigned)time(0)); // sets the rand seed to the clock value
    for(int i=0;i<SIZE;i++)
    {
        rand_NUM[i] = (rand()%SIZE)+1; // random Number equation(domain of x < SIZE && x > 0)
    }

    ofstream arrayData("C:\\array.txt"ios::app); // File Creation(on C drive)

    for(int k=0;k<SIZE;k++)
    {
        arrayData<<"Random Number :"<<rand_NUM[k]<<endl; //Outputs array to txtFile
    }
    return 0;
}
Last edited on Jun 1, 2009 at 11:38pm
May 31, 2009 at 3:01pm
This example demonstrates why you should use a constant when defining an array. It will probably crash in some cases. rand_NUM is a 99 element array so the last value value that can be used with operator[] is 98. Your loop ends when i = 99 and will try to write data to one past the last valid element of the array which results in undefined behavior. The same problem exists with the second for loop. The program might seem to work for a while but it is wrong and could eventually crash. Also, please use the autoformat or beautify feature of your text editor before posting code. It looks so much nicer when properly formatted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
    const int SIZE(100);
    int rand_NUM[SIZE]; 

    srand((unsigned)time(0)); // sets the rand seed to the clock value
    for(int i=0;i<SIZE;i++)
    {
        rand_NUM[i] = (rand()%SIZE)+1; // random Number equation(domain of x < SIZE && x > 0)
    }

    ofstream arrayData("C:\\array.txt"ios::app); // File Creation(on C drive)

    for(int k=0;k<SIZE;k++)
    {
        arrayData<<"Random Number :"<<rand_NUM[k]<<endl; //Outputs array to txtFile
    }
    return 0;
}
Last edited on May 31, 2009 at 3:06pm
Jun 1, 2009 at 11:37pm
yupp your completely right lol
Topic archived. No new replies allowed.