inFile & outFile small problem

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
#include <string>   
#include <iostream>
#include <fstream>
   
using namespace std;
   
//Permutation recursive function
void string_permutation( string& orig, string& perm ){   

    if( orig.empty() ){
		ifstream inFile("new.txt");
		ofstream outFile("new.txt");

        cout << perm << endl;
		outFile << perm << endl;
        return;   
    }   
   
    for( int i = 0 ; i < orig.size() ; ++i ){   
        string orig2 = orig;   
   
		//erase the alphabet
        orig2.erase(i,1);   
   
		//Use another variable to call the recursive function
        string perm2 = perm;   

		//Get back position for original
        perm2 += orig.at(i);   
   
        string_permutation( orig2 , perm2 );   
   
    }    
}   
   
int main(){   
     
    string orig="abc";   
    string perm;

 
    string_permutation( orig,perm );   
   
    cout << "Complete!" << endl;   
   
    system( "pause" );   
   
    return 0;   
} 


i want to ask , i forget how to do since already 1 year. haha
in My
1
2
3
//new.txt

cba //<--The only input 


but actually it should be
1
2
3
4
5
6
7
8
//new.txt <--real answer

abc
acb
bac
bca
cab
cba


what should i do for my ifstream then?
what should i do for my ifstream then?

Nothing, you don't need that.

The problem is that opening your file for writing discards its old content, and you do open it multiple
times, due to the recursive nature of your function. A possible solution would be something like this:

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
#include <string>
#include <iostream>
#include <fstream>

using namespace std;

//Permutation recursive function
void string_permutation_rec( string& orig, string& perm, ostream & outFile) {

    if( orig.empty() ) {
        cout << perm << endl;
        outFile << perm << endl;
        return;
    }

    for( int i = 0 ; i < orig.size() ; ++i ) {

        string orig2 = orig;

        //erase the alphabet
        orig2.erase(i,1);

        //Use another variable to call the recursive function
        string perm2 = perm;

        //Get back position for original
        perm2 += orig.at(i);

        string_permutation_rec( orig2 , perm2, outFile );
    }
}

void string_permutation( string orig ) {

    string perm;
    ofstream fout("new.txt");

    string_permutation_rec(orig, perm, fout);
}

int main() {

    string orig="abc";

    string_permutation( orig );

    cout << "Complete!" << endl;

    system( "pause" );
}
Last edited on
Also you can open your file in append mode:
http://cplusplus.com/reference/fstream/ofstream/ofstream/
But as m4ster r0shi said, opening file multiple times isn't good idea.
Topic archived. No new replies allowed.