【问题标题】:how can i copy string from file to a linked list in C?如何将字符串从文件复制到 C 中的链表?
【发布时间】:2022-01-21 15:51:05
【问题描述】:

大家好,我不能将文本从文件复制到链表,整数没有问题。有我的代码。主要问题是将访问年份和城市名称复制到链接列表中,例如,我是编程新手,但我无法获得很多东西。指针对我来说似乎很难

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

【问题讨论】:

  • strcpy(temp->city,city_name);

标签: c


【解决方案1】:

这一行:

temp->city[K] = city_name;

实际上并不复制字符串。要在 C 中复制字符串,您必须在循环中复制其中的每个字符,或者使用 strcpy()strncpy() 之类的函数。

请记住确保字符串不超过您在目的地的可用空间量。


PS - 如果你有compiled your program with warnings turned on,你的编译器就会有told you 那一行有问题:

source>: In function 'from_file_to_list':
<source>:29:23: warning: assignment to 'char' from 'char *' makes
integer from pointer without a cast [-Wint-conversion]
   29 |         temp->city[K] = city_name;
      |  

【讨论】:

  • @newsenpai: 1. 下次编译时请打开警告。 2.如果有效,请采纳这个答案...
猜你喜欢
  • 1970-01-01
  • 2021-05-24
  • 2016-07-30
  • 2012-08-16
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 2016-04-30
相关资源
最近更新 更多