Re: Writing a .txt file
"Lucress Carol" <incognito.me@gmx.de> ha scritto nel messaggio
news:8833fa2d-9693-41d0-b45b-0f6b0fe3561c@d21g2000prf.googlegroups.com...
Let's see if I can managed to do the same thing by using vector
inspite of arrays....
This is a possible implementation (new comments are identified by // @@ ).
The structure of the code does not change a lot, but using std::vector
instead of raw C++ arrays helps a lot for debugging (e.g. catching array
index out of bounds), etc.
<code>
//////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <fstream> // @@ Write to file
#include <vector> // @@ vector container
// @@
// I would not include all std namespace, but only classes I need
// using namespace std;
using std::cout;
using std::endl;
using std::ofstream;
// @@ array of doubles
typedef std::vector< double > DoubleArray;
// The function RandomNum creates random numbers
// in the range between small and big
// @@ use DoubleArray
void RandomNum(double small, double big ,int p, DoubleArray & array)
{
double range=(big-small)+1;
// @@ I used .at() method to be sure that array indexes
// are bounds-checked.
// If you need super-fast performance, you can still
// use operator[] (not bounds-checked, so less safe,
// but more fast).
for (int i=0; i<p; i++){
array.at(i)=small+int(range*rand()/(RAND_MAX + 1.0));
}
}
//the function AdditionArr Add the elements of an
//array and store the result in a number S
// @@ use const DoubleArray &, because it is read-only parameter
double AdditionArr (const DoubleArray & Arr,int k)
{
int i;
double Sum=0.0;
for (i=0; i<k; i++){
Sum+=Arr.at(i);
}
return Sum;
}
int main()
{
srand((unsigned)time(0));
int p=3;
int j;
double S;
// @@ a robust std::vector
DoubleArray array(3);
// *** Create output file
ofstream outFile;
outFile.open( "I:\\OutFile.txt" );
// @@ code modified to use DoubleArray
for(j=0;j<3;j++){
RandomNum(-1.5,1.5 ,p,array);
S = AdditionArr(array, p);
for (int k=0; k<p; k++){
cout << "array"<<"["<< k << "]" <<" = " << array.at(k) << endl;
}
cout << "S=" << S << endl;
// *** Write to file
outFile << "j=" << j << " S=" << S << endl;
cout << endl;
}
// *** Closes the file
// (The destructor does that, too)
outFile.close();
return 0;
}
//////////////////////////////////////////////////////////////////////////
</code>
Giovanni