[英]Pushing numbers from a text file into a link list
我试图将文本文件中的数字推送到一个链接列表中,该列表可能在多行中有多个数字。 我的输出一团糟,只打印 -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 循环至少看起来像
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;
}
当传递给头节点的指针等于NULL
时,函数display
可以调用未定义的行为。 如果列表只包含一个节点,该函数将不输出任何内容。
该函数可以通过以下方式声明
void display( ll **h )
{
for ( ll *current = *h; current != NULL; current = current->addr )
{
printf("%d\t",current->data);
}
}
使用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, "%d", &temp) != EOF)
{
printf("Temp = %d\n", temp);
push(&head, temp);
}
printf("check");
display(&head);
fclose(fp);
}
尽管如此,仍有改进的余地。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.