问题:
从文本文件中获取文件,并创建邻接表,再进行深度优先遍历。
遇到的问题:
我的程序有时候能正常结束(返回代码为0),有时候会异常结束(返回代码为乱码),我没有修改代码
如图:
异常结束:
正常结束:
我的文本文件内容是:
该文本文件与该程序的c文件放在同一文件夹下。
我的代码:
#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define MAXSIZE 20
typedef struct Branch
{
int index;
struct Branch* next;
}branch;
typedef struct Tnode
{
char data[MAXSIZE];
branch* first;
}tnode;
void create(tnode tree[],char str[],int cnt) //创建邻接表
{
int j, t = 0;
printf("一共有%d个头节点\n", cnt);
for (int i = 0; i < cnt; i++)
{
j = 0;
while (str[t] != '/') //遇到/就开始找换行符\n,并跳转到下一行,录入下一行头节点
{
tree[i].data[j] = str[t];
j++;
t++;
}
tree[i].data[j] = '\0'; //为tree[i].data加入终止符
tree[i].first = NULL;
while (str[t] != '\n') //跳转至下一行,准备录下一行的头节点
t++;
t++;
puts(tree[i].data); //将该行的头节点中的串打印出来以检验头节点的串是否成功录入
}
for (int i = 0; i < cnt; i++)
{
}
}
void DFS(tnode tree[]) //对邻接表进行深度优先遍历
{
}
void visit() //对结点进行访问
{
}
void FillInText(char str[], FILE* fp) //将文件中内容传入str中
{
char ch;
int length = 0;
ch = fgetc(fp);
while (ch != EOF)
{
str[length] = ch;
ch = fgetc(fp);
length++;
}
str[length] = '\0';
}
int getCount(char str[]) //获取邻接表头节点个数
{
int cnt = 0;
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == '\n')
cnt++;
}
return cnt + 1;
}
int main()
{
FILE* fp;
tnode tree[MAXSIZE];
char ch, str[100];
fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("文件打开失败\n");
exit(0);
}
FillInText(str, fp);
printf("文件中的文本内容为:\n");
puts(str);
create(tree, str,getCount(str));
return 0;
}
求指点迷津,不知道为什么一个程序原封不动,有时候能跑,有时候跑不了。