2

我是 C++ 的新手。我想,我试图回答这个问题,但我浪费了很多时间。我想我已经正确地分解了问题。

问题:我可以从文件中读取数据(它必须包含列),但我无法将它从具有两列的文件中读取到对象中。

所以对象函数可以存储它来计算总

// 这就是我所拥有的...任何人都可以帮助我...我知道这可能很简单,但是我很困惑,在继续之前我必须了解数组和类。

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

Class  Payroll

{
private:
int hours;
double rate, gross;

public:
Payroll()     // default constructor
{
    hours = rate = 0;
}

// Set

     void setHours(int h)
{   hours = h;  }

void setRate(double r)

{   rate = r;   }

//  Get 
double getGross (int hours, double rate r])

{
    gross =  hours * rate;
    return gross;
}

};
// trying write a function that take array display results
void showfunction(int array[],int); // lost here too!

int main ()
{

Payroll sevenObjects[7];

const int EMP_RATE = 7 ;// sets number of Employees
const int EMP_HOURS = 7; 
int hours [EMP_HOURS];
double rate [EMP_RATE];
int count ;
ifstream datafile;  //  used to read  data

datafile.open ("payroll.dat");     // Open file
    if( !datafile)
        cout << "error opening data file \n";
    else
    {                                

  /*  i tried  nested and getline, probably wrong. i tried  2D  Array[][] but didnt      know how to pass to member function */          

        for (count = 0 ; count < lines; count++)
           {
            >> hours[count]>>rate[count];      
          cout << hours[count]<<"  " <<rate[count]<< endl;

            }
       }
         datafile.close();
  return 0;
  }

工资单

40.0          10.00
38.5          9.50
16.0      7.50
22.5      9.50
40.0      8.00
38.0      8.00
40.0      9.00
4

1 回答 1

1

首先,你应该改变你的getGross方法:

double getGross()
{
     gross =  hours * rate;
     return gross;
}

其实,最好有CalculateGrossgetGross方法,但这取决于你。

可能最容易理解的读取数据的方式:

for (count = 0 ; count < lines; count++)
{
    int hours;
    double rate;

    // read everything in temporary variables;
    datafile >> hours >> rate;      
    sevenObjects[count].setHours(hours);
    sevenObjects[count].setRate(rate);

}

至于打印功能,您可以设计如下:

void showfunction(Payroll *array, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << "Gross: " << array[i].getGross() << endl;
    }
}
于 2013-10-25T16:40:12.590 回答