私はインベントリ読み込み機能を開発中です。私は複数のファイルを持つプロジェクトに配置したinventory.txtファイルの内容を読みたいと思っています。私が実行すると、すべての製品の製品番号の最初の整数値が取得されますが、製品番号の後にテキストファイルと一致しないデータが破損します。エラーが私のswitch文にあるように見えます。誰かが私のswith文のテキストファイルからデータを引き出す方法を間違って参照してくださいですか?例えば、私のコンソール出力は次のようになります。ファイルポインタは、私がプログラムCを実行すると、間違ったデータを印刷し続けますプログラミング
1000 1.49 3.79 10 A Fish Food
/* Here's my structure, I have this stored in a header file. */
struct inventory_s
{
int productNumber;
float mfrPrice;
float retailPrice;
int numInStock;
char liveInv;
char productName[PRODUCTNAME_SZ];
};
/* Here's the text I'm trying to insert from the inventory.txt file (this is my input file*/
1000, 1.49, 3.79, 10, 0, Fish Food
2000, 0.29, 1.59, 100, 1, Angelfish
2001, 0.09, 0.79, 200, 1, Guppy
5000, 2.40, 5.95, 10, 0, Dog Collar Large
6000, 49.99, 129.99, 3, 1, Dalmation Puppy
/* Here's the function I've built so far */
int readInventory(void)
{
int count = 0; //counts record
int length = 0; //shows length of string after its read
int tokenNumber = 0; //shows which token its currently being worked on
char* token; //token returned by strtok function
struct inventory_s newInventory; //customer record
int sz = sizeof(struct inventory_s) * 2; //string size to read
char str[sz]; //where data is stored
FILE* inventoryFile = fopen("customer.txt", "r"); //opens and reads file
if (inventoryFile == NULL) //if file is empty
{
printf("Could not open data file\n");
return -1;
}
while (fgets(str, sz, inventoryFile) != NULL) //if file is not empty
{
tokenNumber = INVENTORY_FIELD_PRODUCTNUMBER;
length = strlen(str);
str[length - 1] = '\0';
token = strtok(str, ","); //adds space when there is a "," and breaks into individual words
while (token != NULL)
{
switch (tokenNumber)
{
case INVENTORY_FIELD_PRODUCTNUMBER:
newInventory.productNumber = atoi(token);
break;
case INVENTORY_FIELD_MFRPRICE:
newInventory.mfrPrice = atof(token);
break;
case INVENTORY_FIELD_RETAILPRICE:
newInventory.retailPrice = atof(token);
break;
case INVENTORY_FIELD_NUMINSTOCK:
newInventory.numInStock = atoi(token);
break;
case INVENTORY_FIELD_LIVEINV:
(newInventory.liveInv, token);
break;
case INVENTORY_FIELD_PRODUCTNAME:
strcpy(newInventory.productName, token);
break;
}
token = strtok(NULL, ",");
tokenNumber++; //starts the next inventory
}
count++;
printf("%i %.2f %.2f %i %c %s\n", newInventory.productNumber, newInventory.mfrPrice, newInventory.retailPrice, newInventory.numInStock, newInventory.liveInv, newInventory.productName); //prints out in console
}
fclose(inventoryFile);
return 0;
}
'strcpyの(newInventory.liveInv、トークン)' - 'liveInv'はプレーン' char'、char' 'のではない配列である、あなたができるので、 't 'strcpy()'をそれに挿入します。また、その行のすべてのトークンを読み込んだ後ではなく、すべてのトークンを読み込んだ後に 'printf()'行全体を試みます。あなたのコードのどこかに大括弧がありません。入力ファイルは表示されません。 –
私はそれに取り組んでいます。私を助けてくれてありがとう。私は毎回さらに進んでいます。今すぐ印刷することができますが、テキストファイルの1行だけが印刷されます。 – RTriplett