Конструктор Оператор << Устройство и тест динамического массива - PullRequest
0 голосов
/ 19 ноября 2018
#include iostream
#include cmath
#include fstream
#include cstdlib
#include string
using namespace std;
class Device {//Input and store Device Description and Serial Numbers
protected:
 static string  serial_number;
 static string device_description;
public:
 Device() {
     serial_number = ("6DCMQ32");
     device_description = ("TheDell");
 }
 Device(string s, string d) {
     serial_number = s;
    device_description = d;
 }
};
string Device::device_description;
string Device::serial_number;
class Test {//Input and store Test Description, recent day, and month; 
Calculate the next day
   protected:
      static string Test_Description;
      static int recent_month, recent_day, recent_year, new_month;
      static int nmonth, next_month, next_day, next_year, max_day;
   public:
   Test() {
        Test_Description = ("Virtual");
   }
   static void getMonth() {//Calculates the next/new month
    next_month = recent_month + nmonth;
    new_month = next_month % 12;
    if (next_month >= 12) {
        cout << "The next Date: " << new_month << " / ";
    }
    else {
        cout << "The next Date: " << next_month << " / ";
    }
}
static void getDay() {  //Calculates day of next month
          if (new_month == 4 || new_month == 6 || new_month == 9 || new_month == 11) {
         max_day = 30;
     }
     else if (new_month == 2) {
        max_day = 29;
     }
     else {
         max_day = 31;
     }
     if (recent_day > max_day) {
         cout << max_day << " / ";
     }
     else {
         cout << recent_day << " / ";
     }
 }
 static void getYear() {// Calculate the year of next month
     next_year = recent_year + next_month;
     if (next_year >= 12) {
         cout << recent_year + (next_month / 12) << endl;
     }
     else {
         cout << next_year << endl;
     }
 }
 static void getDate() {// Collects the output of each element of next date
     Test::getMonth(), Test::getDay(), Test::getYear();
 }
  };
 string Test::Test_Description;
 int Test::recent_month;
 int Test::recent_day;
 int Test::recent_year;
 int Test::new_month;
 int Test::nmonth;
 int Test::next_month;
 int Test::next_day;
 int Test::next_year;
 int Test::max_day;
 class Lab : public Device, public Test {
 protected:
     static int n;
  public:
 friend istream & operator>>(istream & in, Lab & lab) {// Inputs 
     cout << "Enter Device Desciption and Serial Number: ";
     getline(in, device_description);
     getline(in, serial_number);
     cout << "Enter Test Desciption: ";
     getline(in, Test_Description);
     cout << "Enter the Number of months: ";
     in >> nmonth;
     cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
     in >> recent_month >> recent_day >> recent_year;
     return in;
   }
   friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs 
    everything in Device Class
     out << Lab::device_description << endl;
     out << Lab::serial_number << endl;
     out << Lab::Test_Description << endl;
     getDate();
     return out;
    }
    static void getN() {
     cout << "Enter the number of devices: ";
     cin >> n;
    }
    static void getWrite() {        
     Lab *obj = new Lab[n];
       if (obj == 0) {
         cout << "Memory Error";
         exit(1);
       }
     for (int i = 0; i<n; i++) {
         cin >> obj[i];
         cout << endl;
     }
     ofstream myfile("Device.txt");
     myfile.write((char *)obj, n * sizeof(Lab));
     delete[] obj;      
   }
   static void getRead() {
     ifstream file2("Device.txt");
     Lab *obj2 = new Lab[n];
     if (obj2 == 0) {
         cout << "Memory Error";
         exit(1);
     }
     file2.read((char *)obj2, n * sizeof(Lab));
     for (int i = 0; i < n; i++) {
         cout << obj2[i];
         cout << endl;
     }
     delete[] obj2;
 }
 /*void getSearch(){

 }*/
};
int Lab::n;
void main() {
   Lab L;
   L.getN();
   L.getWrite();
   L.getRead();
   system("pause");
}

Вывод, который я получаю, - TheDell 6DCMQ32, виртуальный, когда я ввел свои данные. Дата верна, единственная проблема - это описание устройства, серийный номер и тестовое устройство.

Проблема с оператором << при чтении файла ввода / вывода, когда он выводит значения в конструкторе </p>

Цель: ввести количество месяцев для следующей даты тестирования устройства с вводом серийного номера, Описание устройства, описание теста, недавняя дата и количество месяцев двух тестов. В конце концов программа должна быть найдена с помощью ввода пользователем серийного номера и следующей даты, если эти два действительно все в устройстве перечислено.

1 Ответ

0 голосов
/ 19 ноября 2018

Если не писать вашу заявку, я сделаю все возможное, чтобы дать вам направление.

#include <iostream> // Note the '<' and '>' this is to specify is a language provided include
// More includes with the same issue...
using namespace std; // this is general considered bad=practice see https://stackoverflow.com/a/1452738/8480874 for details

//Input and store Device Description and Serial Numbers
class Device
{                                        // Notice the white space makes it easier to read...
protected:
   //static string  serial_number; // declaring this static means _EVERY_ device will have the same serial number
   //static string device_description;  // same as above
   string serialNumber;
   string deviceDesc;
public:
   Device() : serialNumber("6DCMQ32"), deviceDesc("TheDell")
   {
     //serial_number = ("6DCMQ32");      // Not the best place for initialization
     //device_description = ("TheDell"); // Not the best place for initialization
   }
   //Device(string s, string d)       // you never actually use this
   //{
   //  serial_number = s;
   //  device_description = d;
   //}
};
//string Device::device_description; // This is a sign that you variable will be shared between everyone - not required if you remove the static
//string Device::serial_number;      // This is a sign that you variable will be shared between everyone - not required if you remove the static



// This suffers from the same probles as the `class device` above
class Test
{
  // Lots of stuff was here just trying to short the answer....
  // Mostly has the same culprits mentions for the device

     // This is one of the fucntions which gets called when you are trying to "save" the info to a file
     static void getMonth(/* ostream & out */) // you need this as a paramater
     {
        next_month = recent_month + nmonth;
        new_month = next_month % 12;

        if (next_month >= 12)
        {
           // This function has no idea is needs to redirect the out put to a file...
           // its only outputting to the standard console
           cout << "The next Date: " << new_month << " / ";
        }
        else
        {
           //cout << "The next Date: " << next_month << " / ";

           // using the new parameter in comments
           // you can now save to your file
           out << /*"The next Date: " <<*/ next_month << " / "; // no I comment out your extra message since you file reading does not look for that
        }
     }
  };


  // Again we have the same general misuse of C++ ( please keep learning! hopefully I am point you in the right direction )
 class Lab : public Device, public Test
 {
 protected:
     static int n;
  public:
 friend istream & operator>>(istream & in, Lab & lab)
 {
    // Inputs 
     cout << "Enter Device Desciption and Serial Number: ";
     getline(in, device_description);
     getline(in, serial_number);
     cout << "Enter Test Desciption: ";
     getline(in, Test_Description);
     cout << "Enter the Number of months: ";
     in >> nmonth;
     cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
     in >> recent_month >> recent_day >> recent_year;
     return in;
   }

   friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs 
    everything in Device Class
     out << Lab::device_description << endl;
     out << Lab::serial_number << endl;
     out << Lab::Test_Description << endl;

     // Here you should pass the output pipe
     getDate(/* out */);

     return out;
    }

    static void getN() {
     cout << "Enter the number of devices: ";
     cin >> n;
    }


    static void getWrite()
    {
       // there's no real need to be using a pointer or memory allocation
       //Lab *obj = new Lab[n];

       // you can simply use
       Lab obj[n];

       //if (obj == 0)
       //{
       //  cout << "Memory Error";
       //  exit(1);
       //}

      for (int i = 0; i < n; i++)
      {
         cin >> obj[i];
         cout << endl;
      }

      ofstream myfile("Device.txt");
      //myfile.write((char *)obj, n * sizeof(Lab)); // I've never tried writting an object's memory as a char* to file

      // usually I like to generate a human readable output 
      std::string objBuffer = obj.getSaveBuffer(); // you will need to implement this `getSaveBuffer()` functions
      myfile << objBuffer; // This can save lots of different value types for you! see http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/

      //delete[] obj; // since there is no more new; we dont need a delete!
   }

   // The logic of what you read suffers the same general issues as the write.
   // Also what/how you read is very far from the save so I can't venture into any solutions
   // I'm hoping this will kick start you to figuring it out on your own =)
   static void getRead() {
     ifstream file2("Device.txt");
     Lab *obj2 = new Lab[n];
     if (obj2 == 0) {
         cout << "Memory Error";
         exit(1);
     }

     file2.read((char *)obj2, n * sizeof(Lab));
     for (int i = 0; i < n; i++) {
         cout << obj2[i];
         cout << endl;
     }
     delete[] obj2;
 }
 /*void getSearch(){

 }*/
};
int Lab::n;


// A program that runs should always return a numeric result indicating success or failure
//void main() {
int main()
{

   Lab L;    // Since everything in all your classes is static this didnt really add anything
             // you done need an object if the object contains nothing

   L.getN();
   L.getWrite();
   L.getRead();

   system("pause"); // this is also bad practice, see https://stackoverflow.com/a/1107717/8480874
   // I personally like `getchar()` because it's easy and quick

}
...