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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include <iostream>
#include <fstream>
using namespace std;
bool connectToInputFile(ifstream& fin, const string& filename);
bool connectToOuputFile(ofstream& fout, const string& filename);
void writeRandomNumbersToFile(const string& filename);
void splitNumbersBySign(const string& inputFilename, const string& posFilename, const string& negFilename);
int main() {
/* Generate the 1000 random numbers in the range -1000 to 1000 and save
* them in a file.
*/
writeRandomNumbersToFile("randomNumbers.txt");
/* Split the random numbers into two files. One containing all the positive
* numbers and the other all the negative numbers.
*/
splitNumbersBySign("randomNumbers.txt", "pos.txt", "neg.txt");
cout << "Both pos.txt and neg.txt have been created successfully." << endl;
cout << endl;
return 0;
}// end main()
bool connectToInputFile(ifstream& fin, const string& filename){
fin.open(filename.c_str());
if (fin.fail()) { return false; }
else return true;
}
bool connectToOuputFile(ofstream& fout, const string& filename){
fout.open(filename.c_str());
if (fout.fail()) { return false; }
else return true;
}
void writeRandomNumbersToFile(const string& filename){
ofstream fout;
if ( !connectToOuputFile(fout, "randomNumbers.txt") ) {
cerr << "Error opening file rand.numbers ";
exit(1);
}
int r;
for(int i=0; i<=1000-1; i++){
r= rand() % 2001-1000;
fout<<r<<" ";
}
cout << "File was written successfully." << endl << endl;
fout.close();
}
void splitNumbersBySign(const string& inputFilename, const string& posFilename, const string& negFilename){
int r;
ofstream foutpos;
ofstream foutneg;
ifstream fin;
connectToInputFile(fin, inputFilename);
connectToOuputFile(foutneg, negFilename);
connectToOuputFile(foutpos, posFilename);
fin >> r;
while ( !fin.eof()) {
if(r < 0){
foutneg<<r<<" "; }
else {
foutpos << r << " ";
}
fin>>r;
}
fin.close();
}
|