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!
#include <iostream>
#include <fstream>
#include <vector>
usingnamespace 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();
}