2013-04-27 106 views
0

我在這裏做錯了什麼?當我發送這個我得到完全空白的文件?我是否需要重新處理數組或者是否實際上不向文件發送任何內容?這是作業,所以有用的提示會很棒。我很困惑,所以很需要幫助。發送輸出到一個數組和一個函數中的兩個文件

Main- #include<iostream> 
#include<fstream> 
#include<string> 
#include "Payroll.h" 
using namespace std; 


const int NUM_EMPLOYEE = 75; 

int main() 
{ 
    int dependents; 
    double payrate; 
    string name; 
    double hours; 
    ifstream fin; 
    int count = 0; 
    Payroll employeeArray[NUM_EMPLOYEE]; 
    ofstream fout; 

    fin.open("employeeData.txt"); 

    if (!fin) 
    { 
     cout << "Error opening data file\n"; 
     return 0; 
    } 
    else 
    { 
     while(fin >> payrate >> dependents) 
     { 
      getline(fin, name); 
      employeeArray[count].setWage(payrate); 
      employeeArray[count].setDependents(dependents); 
      employeeArray[count].setName(name); 
      cout << "How many hours has" << name << " worked? "; 
       cin >> hours; 
       employeeArray[count].setHours(hours); 
      count++; 
     } 

    } 
    fout.open("payrollDetails.txt"); 
    fout << " Name    Hours Regular Overtime Gross Taxes Net" << endl; // heading for file 
    fout.close(); 
    fout.open("checkInfo.txt"); 
    fout << "Net Pay Name"; // heading for file two 
    fout.close(); 

    for (int i = 0; i < count; i++) 
    { 
     employeeArray[i].printPayDetails(fout << endl); 
    } 

    return 0; 
} 

打印功能 -

void Payroll::printPayDetails(ostream& out) 
{ 
    double normPay = getNormPay(); 
    double overTime = getOverPay(); 
    double grossPay = getGrossPay(); 
    double taxAmount = getTaxRate(); 
    double netPay = computePay(); 
    const int SIZE = 9; 
    ofstream fout; 

    fout.open("payrollDetails.txt"); 
    out << setw(19) << left << name << fixed << setprecision(2) << right << setw(5) << hours << setw(SIZE) << normPay << setw(SIZE) << overTime ; 
    out << setw(SIZE) << grossPay << setw(SIZE) << taxAmount <<setw(SIZE) << netPay; 
    fout.close(); 

    fout.open("checkInfo.txt"); 
    out << netPay << "  " << name; 
    fout.close(); 
} 

回答

0

我看到的唯一問題是,你不能清除導致換行符流:

while (fin >> payrate >> dependents) 
{ 
    getline(fin, name); 

在同時執行提取後循環,一個換行符留在流中。 std::getline()將通過調用ignore()停止輸入時,看到換行,所以你要擺脫它:

fin.ignore(); 
getline(fin, name); 

由於ignore()返回流的引用,你甚至可以用它的參數中:

getline(fin.ignore(), name); 

但更習慣是使用std::ws,即丟棄所有前導空格操縱:

getline(fin >> ws, name); 

您還需要將其放在if聲明中以檢查它是否成功:

while (fin >> payrate >> dependents && getline(fin >> ws, name)) 
{ 
    // ... 
相關問題