簡體   English   中英

從C中的文本文件讀取字符串

[英]Reading in character strings from text file in C

我需要編寫一個程序,該程序從文本文件中讀取字符串並將每個單詞存儲在結構中,即,如果文本文件中的第一行是:

豐田COROLLA 2014白色

Toyota將進入structname.model,花冠將進入structname.make,等等。我在將每個字符串讀入結構中的相應元素時遇到了麻煩。 我的源代碼(我沒有在這里發布它的代碼很長,並且很大一部分與這個問題無關)可以正確編譯,但是我有99%的肯定是我的循環有問題,應該是正在讀取以下值:

carRecord cars[10]; //declares array of structs containing carRecord info
char filename[256];
char buf[256];
FILE *carfile;

printf("Please enter the name of a file to read car records from (followed by the file extension): ");
scanf("%s", filename);

carfile = fopen(filename, "r");

if (!carfile)
{
    printf("File failed to open.\n");
}

printf("ERROR CHECK 1");

int i = 0;
while ((fgets(buf, sizeof(buf), carfile) != NULL) && i < 10)
{
    cars[i].make = strdup(strtok(buf, " "));

    cars[i].model = strdup(strtok(buf, " "));

    cars[i].year = atoi(strdup(strtok(buf, " ")));

    cars[i].color = strdup(strtok(buf, " "));

    i++;
}

打印第一個錯誤檢查,然后程序崩潰。 我有一種強烈的恐懼感,這與malloc命令有關,但是我對C還是很陌生,並且完全不知道如何實現它。

如果有幫助,carRecord的結構聲明為:

struct carRecord{
    char* make;     //make of car
    char* model;    //model of car
    int year;           //year of car
    char* color;    //color of car
};

(編輯:代碼已更新,以反映以下評論)

我很確定,如果您將內存分配給結構元素,您將獲得理想的結果。 如您提到的,否則,請使用calloc / malloc。

struct carRecord{
    char make[100];     //make of car
    char model[100];    //model of car
    int year;           //year of car
    char color[100];    //color of car
};

暫無
暫無

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

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