Yester07 2022-06-29 10:39 采纳率: 48.5%
浏览 53
已结题

从文件中获取文本并建树

问题:
从文本文件中获取文件,并创建邻接表,再进行深度优先遍历。
遇到的问题:
我的程序有时候能正常结束(返回代码为0),有时候会异常结束(返回代码为乱码),我没有修改代码
如图:
异常结束:

img

正常结束:

img

我的文本文件内容是:

img

该文本文件与该程序的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;
}

求指点迷津,不知道为什么一个程序原封不动,有时候能跑,有时候跑不了。

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 已结题 (查看结题原因) 6月29日
    • 修改了问题 6月29日
    • 创建了问题 6月29日

    悬赏问题

    • ¥35 平滑拟合曲线该如何生成
    • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 自己瞎改改,结果现在又运行不了了
    • ¥15 链式存储应该如何解决
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站