C语言的问题,各位高手帮忙!

2024-11-05 17:34:31
推荐回答(1个)
回答(1):

若不考虑输入文件的数据错误问题,可以参考以下程序:

#include
#include
#include
#include
#include

typedef struct _node{
int num;
struct _node *next;
}node;

node *head = NULL;

void insert(int num)
{
if (NULL == head)
{
head = (node*)malloc(sizeof(node));
head->num = num;
head->next = NULL;
}
else
{
node* p = head;
while (NULL != p->next) //move to end
{
p = p->next;
}
p->next = (node*)malloc(sizeof(node));
p = p->next;
p->num = num;
p->next = NULL;
}

}

void Writedat()
{
FILE *f = fopen("D:\\data\\tar.txt", "w");
if (NULL == f)return;
if (NULL == head)return;
node *p = head;
while (1)
{
if (p->num != INT_MIN)
{
if ((NULL != p->next) && (INT_MIN != p->next->num))
fprintf(f, "%d, ", p->num);
else
fprintf(f, "%d", p->num);
}
else{
fprintf(f, "\n");
}
p = p->next;
if (NULL == p)break;
}
fclose(f);
}

void Readdat()
{
FILE *f = fopen("D:\\data\\src.txt", "r");
char ch;
char t[100];
int index=0;
memset(t, -1, 100);
do{
ch = fgetc(f);
if (isdigit(ch))
{
t[index++] = ch;
continue;
}
else
{
if (t[0] != -1)
{
insert(atoi(t));
index = 0;
memset(t, -1, 100);
}
switch (ch)
{
case '\n':
if (t[0] != -1)
{
insert(atoi(t));
index = 0;
memset(t, -1, 100);
}
insert(INT_MIN);
break;
default:
break;
}
}
}while (ch != EOF);
fclose(f);
}

void main()
{
Readdat();
Writedat();
}

若一定要以xx[][]代替指针可自行编程序处理