简体   繁体   English

如何将字符串从文件复制到 C 中的链表?

[英]how can i copy string from file to a linked list in C?

Hi guys i can't copy text from a file to linked list, with integers there is no problem.大家好,我无法将文本从文件复制到链表,整数没有问题。 There is my code.有我的代码。 Main problem is to copy year of visit and name of city to a linked list like, I'm new in programming and tbh i can't get a lot of things.主要问题是将访问年份和城市名称复制到链接列表中,例如,我是编程新手,但我无法获得很多东西。 Pointers seems very hard to me指针对我来说似乎很难

#include <stdio.h>
#include <stdlib.h>
#define K 50
typedef struct tourists{
    int year;
    char city[K];
    char country[K];
    struct tourists *next;
}Element;
    typedef Element *List;

List from_file_to_list(char file_name[20])
{
    FILE *file1;
    int x, y;
    char city_name[K];
    List temp, head = NULL;
    
    file1 = fopen(file_name, "r");
    if(file1 == NULL)
    {
        printf("Cannot do that");
        return NULL;
    }
    
    while(fscanf(file1, "%d %s", &x, city_name) != EOF)
    {
        temp = (List)malloc(sizeof(Element));
        temp->city[K] = city_name;
        temp->year = x;
        temp->next = head;
        head = temp;
    }
    return head; 
}

void show_list(List head)
{
    List temp;
    
    temp = head;
    while(temp != NULL)
    {
        printf("%s", temp->city);
        temp = temp->next;
    }
    
}

int main()
{
    List head = NULL;
    head = from_file_to_list("from.txt");`
    show_list(head);
}

This line:这一行:

temp->city[K] = city_name;

doesn't actually copy a string.实际上并不复制字符串。 To copy a string in C, you have to copy each one of its characters in a loop, or alternatively use a function like strcpy() or strncpy() .要复制 C 中的字符串,您必须循环复制其中的每个字符,或者使用 function (如strcpy()strncpy()

Remember to make sure the string is not longer than the amount of space you have available at the destination.请记住确保字符串不长于您在目的地的可用空间量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM