簡體   English   中英

如何將字符串從文件復制到 C 中的鏈表?

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

大家好,我無法將文本從文件復制到鏈表,整數沒有問題。 有我的代碼。 主要問題是將訪問年份和城市名稱復制到鏈接列表中,例如,我是編程新手,但我無法獲得很多東西。 指針對我來說似乎很難

#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);
}

這一行:

temp->city[K] = city_name;

實際上並不復制字符串。 要復制 C 中的字符串,您必須循環復制其中的每個字符,或者使用 function (如strcpy()strncpy()

請記住確保字符串不長於您在目的地的可用空間量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM