C++为什么走迷宫问题不能打印在文本上

来源:百度知道 编辑:UC知道 时间:2024/07/04 13:16:23
/*名称:迷宫(0为可走的路径)*/
/*文件名:迷宫.cpp*/
/**************************/
#include <fstream>
#include<iostream>
using namespace std;
const int Max_ROW=10,Max_COL=10;
int No=0; //路径条数
int sum;
string path;
ofstream outfile;
int maze[Max_ROW][Max_COL];
/***************************/
typedef struct{
int vert;
int horiz;
}offsets;
offsets move[4]={
{1,0},
{0,1},
{-1,0},
{0,-1}

}; //移动顺序,下,右,上,左
/***************************/
//迷宫
bool b[Max_ROW][Max_COL];

string convertString(int i,int j)
{
char s[1];
string t="->(";
sprintf(s, "%d", i);
t=t+s+",";
sprintf(s, "%d", j);
t=t+s+")";
return t;
}

void findpath(int row,int col)
{
int direct,next_row,next_col;
string tempp;
for( direct=0; dir

因为你findpath()函数里的最后一行把outfile给关了。

如果findpath()不是递归函数(就是自己调用自己)的话,你关掉outfile没有问题,但是当它递归的时候,你关掉的outfile又没重新打开,当然要出问题。

改正:

把findpath()最后一行的close语句注释掉即可。

-----

关于编程习惯的建议

1,关于输入输出文件流,如果非要在子函数中用不可,建议将其作为函数参数而不要作为全局变量,因为作为初学者来讲,很容易出现流什么时候忘了打开什么时候又忘了关闭的情况,作为函数参数来做,把流的打开关闭放到函数内部完成,有利于避免这类错误

2,如果非必要,尽量少用goto语句和全局变量