Sending data to an array

First of all, I am a C++ beginner, so please keep your responses VERY basic.

I am working on a project that calls a dataset, reads each value, and then determines whether it is even or odd. This I get. However, after I determine if they are even/odd, if I wanted to send all of the even or odd numbers to a new .dat file, how would I do this?!? Please respond ASAP. Thanks in advance!
I suppose you can best use two array's of vectors for this.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <fstream>
#include <vector>
    
using namespace std;

#define ELEMENTS 10  // Your dataset is probably allready defined.

int dataset[ELEMENTS] = { 0,1,2,3,4,5,6,7,8,9 };

// Declare two vectors with type int.
vector<int> odd;
vector<int> even;

int main()
{
    void split_dataset();
    void save_files();

    split_dataset();
    save_files();

    return 0;
}

void split_dataset()
{
    for( int x=0 ; x<ELEMENTS ; x++ )
    {
        if( dataset[x]%2 == 0 )
        {
            even.push_back( dataset[x] );
        }
        else
        {
            odd.push_back( dataset[x] );
        }
    }
}

void save_files()
{
    fstream outfile;  // declare outfile as a filestream object.

    // open the outfile, ios::trunc to overwrite existing file, ios::out for file output.
    // refer to http://www.cplusplus.com/reference/iostream/fstream/ for more info
    outfile.open("even.txt", ios::trunc |  ios::out);

    // loop that has as many cycles as vector odd has elements.
    // cast to int to prevent signed/unsigned error.
    for( int x=0 ; x<(int)even.size() ; x++ )
    {
        // here the contents of even[x] are binary shifted left onto the outfile stream, 
        // followed by a semicolon ; for separating the values.
        outfile<<even[x]<<";";  
    }
    // after opening the file allways close again.
    outfile.close();

    // same here for vector odd.
    outfile.open("odd.txt", ios::trunc |  ios::out);

    for( int x=0 ; x<(int)even.size() ; x++ )
    {
        // values inside a vector are addressed the same way as accessing an array element
        // see http://www.cplusplus.com/reference/stl/vector/ for class vector member functions.
        outfile<<odd[x]<<";";
    }
    outfile.close();
}


Regards, Ronnie van Aarle.

Topic archived. No new replies allowed.