gpt4 book ai didi

c - 将字符串插入链表无法正常工作

转载 作者:行者123 更新时间:2023-11-30 17:03:35 27 4
gpt4 key购买 nike

我有一个程序,应该获取输入文件并从中提取字符串并将其添加到链接列表中。我认为我没有正确地将字符串添加到链接列表中,而且我似乎找不到正确的方法。当程序执行时,由于某种原因,它会进入无限循环。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct list {
char *string;
struct list *next;
};

typedef struct list LIST;

int main() {
FILE *fp;
char line[128];
char file_name[20];
LIST *current, *head;
char *p, *s;

head = current = NULL;
printf ("Enter the name of the file: ");
scanf("%s",file_name);

fp = fopen(file_name, "r");

while(fgets(line, sizeof(line), fp))
{
p = s = line;
while(*p!=0)
{
if (*p==' ')
{
LIST *node = malloc(sizeof(LIST));
*p = 0;
node->string = strdup(s);
node->next =NULL;

if(head == NULL){
current = head = node;
} else {
current = current->next = node;
}
s = p+1;
}

p++;
}
}
fclose(fp);
//test print
for(current = head; current ; current=current->next){
printf(" %s", current->string);
}
return 0;
}

最佳答案

几件事:

  • 您对一行中的所有单词使用相同的节点,从而创建了一个循环,其中 node->next等于 node 。您应该在插入新单词时创建一个新节点,而不是在读取新行时创建。

  • 你听不懂一行的最后一个单词。您可以利用 fgets 的事实保留尾随换行符并除了检查空格之外还检查该字符。您还可以考虑使用 isspace来自<ctype.h> .

    另一种可能更好的方法是将空终止符的检查推迟到循环之后。当您读到空格或空字符时,您必须添加新单词。

  • 当输入文件包含连续空格或空格字符时,插入空字。你的程序应该检查是否p > s仅添加有效单词。 (或者您的程序应该仅在先前读取的字符不是空格时添加有效单词。)

  • 您为节点和字符串分配内存。你应该free退出程序之前的内存。

这是包含上述修复的主循环:

while(fgets(line, sizeof(line), fp))
{
char *p = line;
char *s = line;

do {
if (*p== ' ' || *p == '\n' || *p == '\t' || *p == '\0') {
if (p > s) {
LIST *node = malloc(sizeof(LIST));

*p = 0;
node->string = strdup(s);
node->next = NULL;

if(head == NULL){
head = node;
} else {
current->next = node;
}
current = node;
}
s = p + 1;
}

p++;
}
while (*p != 0);
}

关于c - 将字符串插入链表无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36111595/

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