2013-04-26 34 views
1

我嘗試了一切,我所知道的是我知道的東西是不正確的,但至少輸出格式是如何爲兩個文件中的一個需要它。我需要將信息發送到兩個獨立的.txt文件中,這兩個文件都帶有不同的信息。我如何使用當前已有的數組函數來做到這一點。我花了數小時試圖弄清楚,現在它取決於你們所有人!謝謝。使用函數和數組寫入兩個文件

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]; 

    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++; 
     } 

    } 

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

    cout << 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; 
    out << fixed << setprecision(2) << right << setw(5) << hours << setw(SIZE) << normPay << setw(SIZE) << overTime ; 
    out << setw(SIZE) << grossPay << setw(SIZE) << taxAmount <<setw(SIZE) << netPay; 
} 
+0

你試圖達到什麼結果?你沒有真正問過一個具體的問題。 此外,這功課? – StilesCrisis 2013-04-26 22:59:42

+0

如果您要問如何將輸出寫入不同的文件,請嘗試使用「C++文件流」搜索 – Bull 2013-04-26 23:05:46

+1

您目前正在打印到標準輸出。你不會將它發送到2個不同的文件。你設法讓'ifstream'工作,所以'ofstream'不應該太難。 – Dukeling 2013-04-26 23:08:57

回答

1

你的問題的措辭是有點不穩,但我想我明白你在說什麼。如果你想輸出到兩個不同的文件,你將需要兩個字符串流。下面是一個例子:

#include <fstream> 

void main() 
{ 
    //Open file 1 
    ofstream file1; 
    file1.open("file1.txt"); 
    file1 << "Writing stuff to file 1!"; 

    //Open file 2 
    ofstream file2; 
    file2.open("file2.txt"); 
    file2 << "Writing stuff to file 2!"; 

    //That the files are open you can pass them as arguments to the rest of your functions. 
    //Remember to use & 


    //At the end of your program remember to close the files 
    file1.close(); 
    file2.close(); 
}