【问题标题】:Writing object array contents to and from file将对象数组内容写入文件和从文件写入
【发布时间】:2016-01-17 00:42:47
【问题描述】:

我目前正在尝试编写程序的一部分,以将数组中的对象读取到文本文件中,反之亦然。我可以让它将对象输出到一个看似没有问题的文件,但是当我尝试将文本文件中的数据读入一个空数组时,它会将最后一个对象放在第一个对象应该在的位置,并将所有其他对象留空。我哪里出错了?

这是我的课程代码

//Defining function for items to file
void Stock::writeToFile(ofstream& fileOut)
{
    fileOut << stockCode << " ";
    fileOut << stockDesc << " ";
    fileOut << currentLevel << " ";
    fileOut << reorderLevel << " ";
}

//Defining function for reading items in from the file
void Stock::readFromFile(ifstream& fileIn)
{
    while (fileIn >> stockCode >> stockDesc >> currentLevel >> reorderLevel)
    {
        fileIn >> stockCode;
        fileIn >> stockDesc;
        fileIn >> currentLevel;
        fileIn >> reorderLevel;
    }
}

这是我在 main 中的代码

#include <iostream>
#include <string>
#include <fstream>
#include "Stock.h"

using namespace std;

int main()
{
    Stock items[4];
    int option = 0;
    cout << "1.Display full stock list." << endl;
    cout << "Please pick an option: ";
    cin >> option;
    switch (option)
    {
    case 1:
        cout << "stockCode" << '\t' << "stockDesc" << '\t' << '\t' << "CurrentLevel" << '\t' << "ReorderLevel" << endl;
        cout << "------------------------------------------------------------------------------" << endl;
        ifstream fileIn;
        fileIn.open("Stock.txt");

        for (int i = 0; i < 4; i++)
        {
            items[i].readFromFile(fileIn);
            cout << items[i].getCode() << '\t' << '\t';
            cout << items[i].getDescription() << '\t' << '\t' << '\t';
            cout << items[i].getCurrentLevel() << '\t' << '\t';
            cout << items[i].getReorderLevel() << endl;
        }
    }
    return 0;
}

【问题讨论】:

  • 值是什么类型?
  • 字符串 stockCode,字符串 stockDesc,int currentLevel,int reorderLevel

标签: c++ arrays file oop


【解决方案1】:

这个循环遍历整个文件,直到它无法再读取,这就是为什么最后一组变量只有一个可见的原因。所有之前的都被覆盖。

  while (fileIn >> stockCode >> stockDesc >> currentLevel >> reorderLevel)
    {
        fileIn >> stockCode;
        fileIn >> stockDesc;
        fileIn >> currentLevel;
        fileIn >> reorderLevel;
    }

第一次在你的 for 循环中,调用

items[i].readFromFile(fileIn);

循环浏览整个文件。 for 循环中的所有剩余迭代,尝试从文件中读取,但它已经在 EOF。

【讨论】:

  • 删除了while循环,它可以工作了!谢谢!有什么我可以替换 for 循环来使这段代码适应各种大小的数组吗?
【解决方案2】:

正如 molbdnilo 指出的那样,您希望按顺序从文件读取到您的库存对象,因此应该删除循环。同样在这种情况下,最好使用自定义友元函数直接从流中读取和写入对象。请参阅下面的代码可以实现这一点。

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


// This what goes into your "Stock.h"
class Stock{

   std::string  stockCode;
   std::string stockDesc;
   int currentLevel;
   int reorderLevel;

  public:

    Stock():currentLevel(0),reorderLevel(0){};
    Stock(std::string const & scode, 
          std::string const & sdesc, 
          int const clevel,
          int const rlevel  
          ):stockCode(scode),
            stockDesc(sdesc),
            currentLevel(clevel),
            reorderLevel(rlevel){}

    friend std::istream& operator >>(std::istream& is, Stock&  stk)
    {
       if (is) { 
          is 
             >> stk.stockCode 
             >> stk.stockDesc 
             >> stk.currentLevel 
             >> stk.reorderLevel;
       }
       return is;
    }

    friend std::ostream& operator <<(std::ostream& os, Stock const& stk)
    {
       os 
          << stk.stockCode << ' '
          << stk.stockDesc << ' '
          << stk.currentLevel << ' '
          << stk.reorderLevel
          << '\n' //Line break after every object so that you can open and read.
          ;
    }
};

//This is your main code with the read loop fixed.


int main()
{
    const int N = 4;
    Stock items[N];

    //1. Create 4 Stock objects.
    items[0] = Stock("A", "STKA", 100, 100);
    items[1] = Stock("B", "STKB", 101, 101);
    items[2] = Stock("C", "STKC", 102, 102);
    items[3] = Stock("D", "STKD", 103, 103);

    //2. Write the 4 Stock objects to a file.

    std::ofstream ofs;
    ofs.open("Stock.txt", std::ofstream::out);
    for ( int i = 0; i < N ; ++i ) { 
       ofs << items[i] ;
    }

    ofs.close();

    // 3. Read from the file written in 2. and print.

    std::ifstream fileIn;
    fileIn.open("Stock.txt");

    Stock stk;
    while (fileIn >> stk) {
       std::cout << stk;
    }
    fileIn.close();
}

输出是:
STKA 100 100
B STKB 101 101
C STKC 102 102
D STKD 103 103

【讨论】:

  • 我还可以通过它显着改进我的程序,谢谢!如果可以的话,我会 +rep 你们。
【解决方案3】:

您将整个文件读入第一个Stock,甚至读取每个Stock 的数据两次。

剩余库存失败,因为您已到达文件末尾。

readFromFile 中删除循环。

【讨论】:

    【解决方案4】:

    对于每个项目,您都在循环直到到达Stock::readFromFile() 中的文件末尾。您需要删除那里的循环:

    //Defining function for reading items in from the file
    void Stock::readFromFile(ifstream& fileIn)
    {
        fileIn >> stockCode;
        fileIn >> stockDesc;
        fileIn >> currentLevel;
        fileIn >> reorderLevel;
    }
    

    所以,剩下的项目就没有什么可读的了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 2014-02-17
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 2016-01-06
      • 2015-05-15
      相关资源
      最近更新 更多