Here's my problem. I've written a program to do some permutation stuff...though the process isn't really relevant. As I worked on it, I always had it "cout" the data to the screen, although eventually I need it to write this info to a text file.
I've done this before, and it's worked fine. I #include <fstream> and then give a command in the main function to ofstream myfile; and myfile.open("filename.txt"); Then change my "cout"s to "myfile"s, and bingo. Works like a charm!
Problem is, I'm trying a modular approach to programming (I think that's the right word), where I have a "static void" function that does the work for me. I haven't had any luck getting it to write to the file.
Here's my code:
[code=c++]
#include <iostream>
#include <fstream>
using namespace std ;
static void show_perm ( int *positions , int position_count )
{
int check1 = 0;
int check2 = 0;
int check3 = 0;
ofstream myfile;
myfile.open ("PermsWithRepeats.txt");
for ( int j = 0 ; j < position_count ; j++ )
{
if (positions[j] == 1)
{
check1 = 1;
}
if (positions[j] == 2)
{
check2 = 1;
}
if (positions[j] == 3)
{
check3 = 1;
}
}
if (check1 == 1 && check2 == 1 && check3 == 1)
{
for (int i = 0; i < position_count; i++)
myfile << positions[i] ; // if these two lines say "cout" instead of "myfile," the info comes up on the display just fine.
myfile << endl ;
}
}
static void show_perms (int *values, int value_count, int *positions, int position_count, int filled_positions)
{
if ( filled_positions == position_count )
{
show_perm ( positions , position_count ) ;
return ;
}
filled_positions ;
for ( int i = 0 ; i < value_count ; i++ )
{
positions [ filled_positions ] = values [ i ] ;
show_perms ( values, value_count, positions, position_count, filled_positions + 1 ) ;
}
}
int main ( )
{
int values[] = {1,2,3};
int positions[4];
show_perms ( values , 3 , positions , 4 , 0 ) ;
return 0 ;
}
[/code]
The program runs, and it even creates the file "PermsWithRepeats.txt," but the file is empty -- nothing gets written to it. I'm sure it's something obvious that I'm missing. Can anyone help?
I'm guessing that it opens the file each time it goes through static void show_perm and writes over what was in there already. On the last time through the show_perm function, it returns a value that is not supposed to be displayed, because of the if statement in line 29. So that's why the file is empty. (I think)
How can I get it to open the file once, and then add to it each time through the show_perm function? (if that is indeed what's happening)