因此,我正在編寫一個程序,它將CSV txt文件中的數據轉換爲數組結構。這些數據將用於管理清單。我讓我的整個程序都能正常工作,但每次運行時突然崩潰。我已經把崩潰縮小到了我的文件閱讀功能,並想知道是否有人能看到這個問題。這是最初的文件數據。將CSV文件讀取到結構數組
1000,1.49,3.79,10,0,Fish Food
2000,0.29,1.59,100,1,Angelfish
2001,0.09,0.79,200,0,Guppy
5000,2.40,5.95,10,0,Dog Collar (Large)
6000,49.99,129.99,3,1,Dalmatian Puppy
這裏是結構減速
struct inventory_s
{
int productNumber;
float mfrPrice;
float retailPrice;
int numInStock;
char liveInv;
char productName[PRODUCTNAME_SZ];
};
結構陣列
struct inventory_s inventory[MAX_INVENTORY];
這裏是我有
FILE* pFile;
char *buf = malloc(MAX_INVENTORY);
char *info;
if ((pFile = fopen("inventory.txt", "r")) == NULL) //Reading a file
{
printf("File could not be opened.\n");
}
int i = 0;
while (fgets(buf, MAX_INVENTORY, pFile) != NULL)
{
if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n'))
buf[strlen (buf) - 1] = '\0';
info = strtok(buf, ",");
inventory[i].productNumber = atoi(info);
info = strtok(NULL, ",");
inventory[i].mfrPrice = atof(info);
info = strtok(NULL, ",");
inventory[i].retailPrice = atof(info);
info = strtok(NULL, ",");
inventory[i].numInStock = atoi(info);
info = strtok(NULL, ",");
inventory[i].liveInv = *info;
info = strtok(NULL, ",");
strcpy(inventory[i].productName, info);
i++;
}
fclose(pFile);
return 0;
調試此類問題的方法是使用調試器。對於初學者,總是檢查'strtok'的每個返回值來驗證它沒有失敗。 – kaylum
最後沒有添加額外的空行嗎?正如kaylum所說,你的代碼對格式不正確的行不健壯。 –
如何開始學習C?上次你問了很多很多相同的基本問題(更改用戶帳戶)。得到一本C書,這沒有輔導。家庭作業幫手網站。你需要先自己做一些努力。 – Olaf