微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将数字从文本文件推送到链接列表

如何解决将数字从文本文件推送到链接列表

我正在尝试将数字从文本文件推送到链接列表中,该列表可能在多行中具有多个数字。我的输出是一团糟,只能打印-47次。我主要的疑问是如何从文件中读取2位数字,尽管我当前的代码甚至没有读取任何数字。

我的代码

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

typedef struct linklist
{
     int data;
     struct linklist *addr;
}ll;

void push(ll **h,int val);
void display(ll **h);


void main()
{
    FILE *fp;
    fp=fopen("re.txt","r");
    char c;
    ll *head=NULL;

    while(c=fgetc(fp)!=EOF)
    {
        if(c==' ' || c=='\n')
        {
            continue;
        } 
        else
        {
            int temp=c-'0';
            printf("Temp = %d",temp);
            push(&head,temp);
        }
    }
    printf("check");
    display(&head);
    fclose(fp);
}

void push(ll **h,int val)
{

    if(*h==NULL)
    {
        ll *temp=(ll*)malloc(sizeof(ll));
        temp->data=val;
        temp->addr=NULL;
        *h=temp;
    }
    else
    {
        ll *current = *h;
        while(current->addr!=NULL)
            current=current->addr;
        current->addr=(ll*)malloc(sizeof(ll));
        current->addr->data=val;
        current->addr->addr=NULL;      
    }
}

void display(ll **h)
{
    ll *current=*h;
    while(current->addr!=NULL)
    {
        printf("%d\t",current->data);
        current=current->addr;
    }
}

编辑:

re.txt文件如下所示:

4
2 1 8 19
6 11 50 89
21 22 47
25 35

解决方法

对于初学者,while循环中的条件

while(c=fgetc(fp)!=EOF)

不正确。等同于以下条件

while( c = ( fgetc(fp) != EOF ) )

因此,如果fgetc( fp )不等于EOF,则表达式fgetc( fp ) != EOF的值为1,变量c将获得此值{{1} }。

while循环至少看起来像

1

变量while( ( c = fgetc(fp) ) != EOF ) 的类型应为c

int

否则,循环可能是无限的,因为类型int c; 可以像类型char一样(取决于编译器的选项),并且变量unsigned char永远不会等于c的签名值。

但是在任何情况下,此循环都是错误的,因为函数EOF还会读取空白字符,而您需要读取整数。

所以像这样改变循环

fgetc

函数int temp; while ( fscanf( fp,"%d",&temp ) == 1 ) { push( &head,temp ); } 看起来也更简单。并且它可以向调用者发出信号,通知是否为新节点成功分配了内存,否则在内存分配失败的情况下,该函数可以调用未定义的行为。例如

push

当传递到头节点的指针等于int push( ll **h,int val ) { ll *temp = malloc( sizeof( ll ) ); int success = temp != NULL; if ( success ) { temp->data = val; temp->addr = NULL; while ( *h != NULL ) h = &( *h )->addr; *h = temp; } return success; } 时,函数display可以调用未定义的行为。如果列表仅包含一个节点,该函数将不会输出任何内容。

可以通过以下方式声明该功能

NULL
,

使用fscanf为您完成工作。

您想要这个:

int main()
{
  FILE* fp;
  fp = fopen("re.txt","r");
  if (fp == NULL)
  {
     printf("Can't open file\n");
     return 1;
  }
  char c;
  ll* head = NULL;
  int temp;

  while (fscanf(fp,&temp) != EOF)
  {
    printf("Temp = %d\n",temp);
    push(&head,temp);
  }
  printf("check");
  display(&head);
  fclose(fp);
}

尽管仍有改进的空间。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。