2016-08-07 5 views
0

Я занимаюсь разработкой функции инвентаризации чтения. Я хочу, чтобы он читал содержимое в файле 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; 
} 
+2

'зЬгср (newInventory.liveInv, маркер)' - 'liveInv' является простым' char', а не массив 'char', так что вы можете 't 'strcpy()' в него. Также вы пытаетесь «printf()» всю строку после прочтения каждого токена, а не после того, как вы прочитали все токены в этой строке. Вам не хватает закрывающей скобки где-то в вашем коде. Вы не показываете нам свой входной файл. –

+0

Я работаю над этим. Спасибо, что помогли мне. Я все больше и больше каждый раз. Теперь я могу распечатать его, но распечатывается только одна строка текстового файла. – RTriplett

ответ

0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define INVENTORY_FIELD_PRODUCTNUMBER 1 
#define INVENTORY_FIELD_MFRPRICE  2 
#define INVENTORY_FIELD_RETAILPRICE 3 
#define INVENTORY_FIELD_NUMINSTOCK  4 
#define INVENTORY_FIELD_LIVEINV  5 
#define INVENTORY_FIELD_PRODUCTNAME 6 

//defines the sizes of the contents in the structure 
#define PRODUCTNAME_SZ 20 

int main() 
{ 
    struct inventory_s 
    { 
     int productNumber; 
     float mfrPrice; 
     float retailPrice; 
     int numInStock; 
     char liveInv; 
     char productName[PRODUCTNAME_SZ]; 
    }; 

    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("inventory.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 

     } 

     printf("%i %.2f %.2f %i %c %s\n", newInventory.productNumber, newInventory.mfrPrice, newInventory.retailPrice, newInventory.numInStock, newInventory.liveInv, newInventory.productName); //prints out in console 
     count++; 

    } 
    fclose(inventoryFile); 
    return 0; 
} 
+0

Придумал! У меня было fclose(), закрывающее файл, прежде чем он смог прочитать следующую строку ввода. Спасибо всем за помощь в том, чтобы помочь мне разобраться. – RTriplett