Search code examples
c++recursionofstream

How do you write multiple lines in a .txt with recursion?


Im a programming student and the Engineer told us to write an algorithm using recursion for the math problem "Hanoi Towers". That is done, Im able to print the instructions on the console, but I need to write the instructions on a .txt file. I have managed to create the file and write the first line of text on it, but the rest doesn't really appear. I really need some help with this guys.

using namespace std;

void torresdehanoi(int disco, int torre1, int torre2, int torre3){
    ofstream myFile;
    myFile.open("SolucionTorresDeHanoi.txt");
    if(disco==1){
        myFile<<"Mover disco de Torre "<<torre1<<" a la torre "<<torre3<<endl;
    }
    else{
        torresdehanoi(disco-1, torre1, torre3, torre2);
        myFile<<"Mover disco de Torre "<<torre1<<" a la torre "<<torre3<<endl;
        torresdehanoi(disco-1, torre2, torre1, torre3);
    }
}

int main()
{
    int disco=0, torre1=1, torre2=2, torre3=3;

    cout<<"Con cuanteas piezas desea calcular el algoritmo?"<<endl;
    cin>>disco;
    torresdehanoi(disco, torre1, torre2, torre3);

    return 0;
}

Solution

  • Open the fstream object from main to make things easy:

    void torresdehanoi(int disco, int torre1, int torre2, int torre3, ofstream& myFile) {
    
        if (disco == 1) {
            myFile << "Mover disco de Torre " << torre1 << " a la torre " << torre3 << endl;
        }
        else {
            torresdehanoi(disco - 1, torre1, torre3, torre2, myFile);
            myFile << "Mover disco de Torre " << torre1 << " a la torre " << torre3 << endl;
            torresdehanoi(disco - 1, torre2, torre1, torre3, myFile);
        }
    }
    
    int main()
    {
        ofstream myFile;
    
        int disco = 0, torre1 = 1, torre2 = 2, torre3 = 3;
    
        cout << "Con cuanteas piezas desea calcular el algoritmo?" << endl;
        cin >> disco;
    
        myFile.open("SolucionTorresDeHanoi.txt");
        if (myFile.is_open()) {
            torresdehanoi(disco, torre1, torre2, torre3, myFile);
            myFile.close();
        }
        return 0;
    }