Okay, sorry if this is considered a duplicate but it is a different problem with the same code discussed in another thread.
I have two problems:
1. my test file is only 7 lines. When I run my code, not all of the lines are outputted into the other text file like they should be. Some are, in a random order (which is correct). It varies between 1 and 6 out of 7 lines so far. I cannot figure out the problem.
2. I want my program to run through a loop; read from one file, randomize it and output it into another file; next pass, read from the 2nd file and randomize again and input back into the first file (rinse and repeat).
I tried using
flush();
but it was not working properly.
If anyone can help with either problem I would be very appreciative. To be honest, most of this code is over my head, but I'm trying to understand it.
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
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <ctime>
#include <cstdlib>
#include <algorithm>
using namespace std;
std::vector<std::streamoff> get_offsets( std::istream& file )
{
std::vector<std::streamoff> offsets( 1, 0 ) ;
file >> std::noskipws ;
std::streamoff pos = 0 ;
char c ;
while( file >> c )
{
pos = pos + 1 ;
if( c == '\n' ) offsets.push_back(pos) ;
}
file.clear() ;
return offsets ;
}
void write( std::istream& in, std::ostream& out,
const std::vector<std::streamoff>& offsets )
{
for( std::size_t i = 0 ; i < offsets.size() ; ++i )
{
in.seekg( offsets[i] ) ;
std::string line ;
if( std::getline( in, line ) && !line.empty() ) out << line;
}
}
int main()
{
std::ifstream file1("Text1.txt", std::ios::binary ) ;
std::ofstream file2("Text2.txt");
std::vector<std::streamoff> offsets = get_offsets(file1) ;
std::srand( (unsigned)time(0) ) ;
std::random_shuffle( offsets.begin(), offsets.end() ) ;
write( file1, file2, offsets ) ;
return(0);
}
|
That is all of the code. Here is my code to run the loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
int zq=0;
for (zq=0; zq<=4; zq++)
{
if (zq%2==0)
{
std::ifstream file1("Text1.txt", std::ios::binary ) ;
std::ofstream file2("Text2.txt");
std::vector<std::streamoff> offsets = get_offsets(file1) ;
std::srand( (unsigned)time(0) ) ;
std::random_shuffle( offsets.begin(), offsets.end() ) ;
write( file1, file2, offsets ) ;
}
else
{
std::ifstream file1("Text2.txt", std::ios::binary ) ;
std::ofstream file2("Text1.txt");
std::vector<std::streamoff> offsets = get_offsets(file1) ;
std::srand( (unsigned)time(0) ) ;
std::random_shuffle( offsets.begin(), offsets.end() ) ;
write( file1, file2, offsets ) ;
}
}
|
I excluded my use of
flush;
because it wasn't working. I read up on it and thought I used it the same as the example but it had an error.
*And by "my" code, I actually mean "someone wrote this code for me and I am trying to wrap my head around it and make it do exactly what I want. :)".