c - 字符串链表仅打印最后输入

标签 c string linked-list

我已经被这个问题困扰了一段时间了,有人可以帮忙吗? 我的链表代码对于整数工作正常,但似乎不适用于字符串,它只打印最后一个条目,知道吗? 谢谢

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

typedef struct node {
   char* val; 
   struct node* next;
 }node;

int main(){

// read text file
FILE * fp;
fp = fopen ("dict.txt", "r");

//  linked list

char i[10];

node* head = malloc(sizeof(node));
node* cursr=head;

while (fscanf(fp, "%s", i) !=EOF)
{
    fscanf(fp, "%s", i);
    //strcpy(cursr -> val,i);
    cursr -> val = i;
    printf("Read String1 |%s|\n", cursr->val );
    node* newnode = malloc(sizeof(node));
    cursr -> next = newnode;
    cursr = newnode;
}

cursr->next = NULL;
cursr=head;

while  (cursr -> next != NULL)
{
    printf("%s",cursr->val);
    cursr = cursr -> next;
}

}

最佳答案

试试这个。它会起作用的。

#include<stdlib.h>
#include<stdio.h>
//#include "node.h"
#include <string.h>

typedef struct node {
   //char* val;
   char val[10];
   struct node* next;
 }node;

int main(){

// read text file
FILE * fp;
fp = fopen ("dict.txt", "r");

//  linked list

char i[10];
//int i;

node* head = malloc(sizeof(node));
node* cursr= head;

while (fscanf(fp, "%s", i) !=EOF)
{
    //fscanf(fp, "%s", i);
    strcpy(cursr -> val,i);
    //cursr -> val = i;
    printf("Read String1 |%s|\n", cursr->val );
    node* newnode = malloc(sizeof(node));
    cursr -> next = newnode;
    //cursr = newnode;
    cursr = newnode;
}

cursr->next = NULL;
cursr=head;

while  (cursr -> next != NULL)
{
    printf("%s",cursr->val);
    cursr = cursr -> next;
}

}

关于c - 字符串链表仅打印最后输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32093235/

相关文章:

c - 将数据输出到文本文件的问题

c - 了解堆栈上变量的空间分配

php - 如何评估在 PHP 中作为字符串传递的公式?

sql - SQL查询删除包含字符串部分的条目?

java - 删除链表中大于运行时用户输入值的所有元素

c - 带有 clang 的宏中未使用的函数

c - 递增指针而不是递增数组及其索引

c - C 中的字符串反转不起作用

c - 打印从我的链接列表中删除值

c - 链表未定义行为