如何使用递归在 .txt 中写入多行?

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

我是一名编程学生,工程师告诉我们使用递归编写算法来解决数学问题 "Hanoi Towers"。完成后,我可以在控制台上打印说明,但我需要将说明写在 .txt 文件上。我设法创建了文件并在上面写了第一行文本,但其余部分并没有真正出现。我真的需要这些家伙的帮助。

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;
}

从 main 打开 fstream 对象使事情变得简单:

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;
}