gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:44:51 24 4
gpt4 key购买 nike

我是一名编程专业的学生,​​工程师告诉我们使用递归编写算法来解决数学问题“汉诺塔”。完成后,我可以在控制台上打印说明,但我需要将说明写在 .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;
}

关于c++ - 如何使用递归在 .txt 中写入多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57533685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com