从文件填充结构 [英] Filling structure from a file

查看:71
本文介绍了从文件填充结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在学校做一个项目,我需要用文本文档中的信息填充指针数组:

Hey guys i am doing a project at school and i need to fill an array of pointers with info from a text doc:

4101 BRAEBURN_REG 1 0.99 101.5
4021 DELICIOUS_GDN_REG 1 0.89 94.2
4020 DELICIOUS_GLDN_LG 1 1.09 84.2
4015 DELICIOUS_RED_REG 1 1.19 75.3
4016 DELICIOUS_RED_LG 1 1.29 45.6
4167 DELICIOUS_RED_SM 1 0.89 35.4
4124 EMPIRE 1 1.14 145.2
4129 FUJI_REG 1 1.05 154.5
4131 FUJI_X-LGE 1 1.25 164.1
4135 GALA_LGE 1 1.35 187.7
4133 GALA_REG 1 1.45 145.2
4139 GRANNY_SMITH_REG 1 1.39 198.2
4017 GRANNY_SMITH_LGE 1 1.49 176.5
3115 PEACHES 1 2.09 145.5
4011 BANANAS 1 0.49 123.2
4383 MINNEOLAS 1 0.79 187.3
3144 TANGERINES 1 1.19 135.5
4028 STRAWBERRIES_PINT 0 0.99 104
4252 STRAWBERRIES_HALF_CASE 0 3.99 53
4249 STRAWBERRIES_FULL_CASE 0 7.49 67
94011 ORGANIC_BANANAS 1 0.99 56.3

因此,我必须将其放入结构中.这是我的功能:

So i have to take that a put it in to a struct. Here is my function doing so:

bool readInventory(string filename)
{
   inputFile.open(filename);   //opening products file
   bool errors = true;

   if(!inputFile.fail()) // validate that the file did open
   {

   while (!filename)      // Dynamically creates array and fills with info 
      { 
          product *inventory = new product();
          inputFile >> inventory->plu;
          inputFile >> inventory->itemName;
          inputFile >> inventory->saleType;
          inputFile >> inventory->price;
          inputFile >> inventory->currentInventory;
          itemArray[counter] = inventory;
          counter++;
        cout << itemArray[14]<< endl;
      }

   }

   else
   {
      cout << "\nError, unable to open products.txt.\n";
      errors = false;
      return errors;
   }

}// ends readInventory

它不会填充数组,但是如果我做while (filename) // Dynamically creates array and fills with info,它将仅将第一个项目记录到数组中,而将其他项保留为空白.我还需要验证输入. (即PLU代码不是整数,但plu类型为字符串),并跳过有问题的乘积并将bool errors从true更改为false.这是我的整个代码:

It wont fill in the array, but if i do while (filename) // Dynamically creates array and fills with info it will record the first item into the array only, leaving the others blank. I also need to validate the input. (i.e the PLU code is not an integer, the plu type is string though) and skip product with problems and change the bool errors from true to false. Here is my whole code:

#include <iostream>
#include <string>
#include <fstream>
#include <cctype>

using namespace std; 

bool readInventory(string filename);
double checkout();
bool updateInventory(string filename);
// prototypes

int counter = 0; //used to fill the array
ifstream inputFile;            //file to read from
const int SIZES = 100; //constant int used to tell sizes
product *itemArray[SIZES]; //array of pointers of size 100
struct product
      {
         string plu;             //price look up code for each product
         string itemName;        //name of item
         int saleType;           //item is per pound or per unit
         int price;              //price of item 
         int currentInventory;   //amount in stock
      };


int main ()
{     
   int choice;           // choice is used to find out what choice they want in the menu.

   bool menuOn = true;   //menuOn is used to turn on and off the menu.

   readInventory("Products.txt");

   while (menuOn == true)
   {
      cout << "1 - Check out.\n";
      cout << "2 - Close the store and exit.\n";
      cout << "Enter your choice and press return: ";
      //Displays choices for the menu

      cin >> choice;  //Chose what menu option you want

      cout << endl;

      switch (choice)
      {

         case 1:

         checkout();

         break;

         case 2:

         cout << "Thank you for using this item check out program.";
         menuOn = false;

         break;

         default:
         cout << "Not a Valid Choice. \n";
         cout << "Choose again.\n\n";
         break;
         // Safty net if user doent enter choice 1-2

     }
  }

   inputFile.close();

   cout << endl; 
   system("pause"); 
   return 0; 

} // end function main () 

bool readInventory(string filename)
{
   inputFile.open(filename);   //opening products file
   bool errors = true;

   if(!inputFile.fail()) // validate that the file did open
   {

   while (counter < 22)   // Dynamically creates array and fills with info 
      { 
          product *inventory = new product();
          inputFile >> inventory->plu;
          inputFile >> inventory->itemName;
          inputFile >> inventory->saleType;
          inputFile >> inventory->price;
          inputFile >> inventory->currentInventory;
          itemArray[counter] = inventory;
          counter++;
      }

   }

   else
   {
      cout << "\nError, unable to open products.txt.\n";
      errors = false;
      return errors;
   }

}// ends readInventory

double checkout()
{
   double total = 0; //total cost
   string pluCode; // code to look for
   bool found = false; // notify if item is found
   double costs;
   double quantity;
   bool codeValid = true;

   do
   {    

       cout << "Please enter PLU code or 0 to exit: ";
       codeValid = true;
       cin >> pluCode;
    /*   for (int x = 0; x <= pluCode.length(); x++)
        {
           if ((pluCode[x] != '1') && (pluCode[x] != '2') && (pluCode[x] != '3') && (pluCode[x] != '4') && (pluCode[x] != '5') && (pluCode[x] != '6') && (pluCode[x] != '7') && (pluCode[x] != '8') && (pluCode[x] != '9') && (pluCode[x] != '0'))
           {
                codeValid = false;
           }

        }   */


      for (int itemFind = 0 ; itemFind < counter; itemFind++)
      {
          if (itemArray[itemFind]->plu == pluCode)
          {
              found = true;
              costs = itemArray[itemFind]->price;
              cout << "Please enter lbs or quantity: ";
              cin >> quantity;
              if (costs); // Data Validation
              costs = quantity*costs;
              total += costs;
          };

      };
      if(!found)
      {
          cout << "Please enter a valid PLU code.\n";
      }

   } while (pluCode != "0");

   if (total > 50.00)
      total = (.95*total);

   return total;
   return 0.00;
}//ends Checkout

bool updateInventory(string filename)
{
   return true;
}//ends updateInventory

如果有人需要,这里是指向实际作业的链接: https://www .dropbox.com/s/howsf5af2gsa1i8/CS1Asg4BStructures.docx

Here is a link to the actual assignment if anyone needs it: https://www.dropbox.com/s/howsf5af2gsa1i8/CS1Asg4BStructures.docx

推荐答案

要从文件中读取所有行,请使用以下代码:

To read all the lines from the file use the following code:

std::string line;
while (std::getline(inputFile,line))
{   
    std::istringstream iss(line);
    product *inventory = new product();
    iss >> inventory->plu;
    iss >> inventory->itemName;
    iss >> inventory->saleType;
    iss >> inventory->price;
    iss >> inventory->currentInventory;

    itemArray[counter] = inventory;
    ++counter;
}

还尝试摆脱全局变量定义(例如counterinputFile),并将其作为函数局部变量或参数提供(或者对于counter,使用它作为返回值甚至是合理的)值:对于错误情况,返回0-1,否则返回读取的记录数).另外,在分配新记录并将其分配给itemArray[counter]之前,您还需要检查counter小于SIZES.

Also try to get rid of the global variable definitions (e.g. counter, inputFile) and provide them as function local variables or parameters (or in case for counter it could be even reasonable to use it as return value: return 0 or -1 for error cases, and the number of records read otherwise). Also you'll need to check that counter is less than SIZES before allocating a new record and assign it to itemArray[counter].

我建议至少使用std::vector来管理记录:

I would recommend at least using a std::vector to manage the records:

std::vector<product> itemArray;

// ... 

std::string line;
while (std::getline(inputFile,line))
{   
    std::istringstream iss(line);
    product newProd;
    iss >> newProd.plu;
    iss >> newProd.itemName;
    iss >> newProd.saleType;
    iss >> newProd.price;
    iss >> newProd.currentInventory;

    itemArray.push_back(newProd);
}

无需使用此代码的counteritemArray.size()就会告诉您从文件读取的记录数.

No need for counter with this code, itemArray.size() will tell about the number of records read from the file.

这篇关于从文件填充结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆