大家好,我無法將文本從檔案復制到鏈表,使用整數沒有問題。有我的代碼。主要問題是將訪問年份和城市名稱復制到一個鏈表中,例如,我是編程新手,但我不能得到很多東西。指標對我來說似乎很難
#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);
}
uj5u.com熱心網友回復:
這一行:
temp->city[K] = city_name;
實際上并不復制字串。要在 C 中復制字串,您必須在回圈中復制其中的每個字符,或者使用類似strcpy()或的函式strncpy()。
請記住確保字串不長于您在目的地可用的空間量。
PS - 如果您在打開警告的情況下編譯了程式,您的編譯器會告訴您該行存在問題:
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;
|
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386832.html
標籤:C
上一篇:C自動將空字符附加到字串?
下一篇:C中字符陣列的快速排序陣列
