2017-09-14 77 views
-4

我是C++的新手,我有我的第一個任務。我們有一個文本文件,其中包含5個員工姓名,工資和工作時間。如何將項目添加到輸出文件?

這是我的代碼,以便我的程序可以讀取它。

#include <iostream> 
#include <fstream> 
#include <iomanip> 
#include <string> 
#include <vector> 

using namespace std; 

int main() 
{ 
    ifstream input; 
    ofstream output; 

    string name; 
    int h; 
    float w; 
    int numEployee = 0; 
    double maxPay, minPay, avgPay; 
    int gross, adjGross; 

    //input/output file document path 
    input.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employees.txt"); 
    output.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employeesoutput.txt"); 

    //checks if the input file is working 
    if (input.fail()) 
    { 
     cout << "Input file failed to open." << endl; 
     system("pause"); 
     exit(0); 
    } 

    //checks if output file is working 
    if (output.fail()) 
    { 
     cout << "Output file failed to open." << endl; 
     system("pause"); 
     exit(0); 
    } 

    //prints the name, wage, hours worked of the employees to the output file 
    while (input >> name >> w >> h) 
    { 
     output << setw(5) << name << setw(5) << w << setw(5) << h << endl; 
    } 


    system("pause"); 
    return 0; 
} 

它正確地閱讀它,並給我輸出文件,我想要但缺少項目。完整的輸出文件應該有員工人數,最高工資,最低工資,平均工資,總工資和調整總額。

任何人都可以幫助我指向正確的方向嗎?

感謝

+0

以下是您需要創建[mcve]的說明。只要問問自己以下問題:有人可以拿出你在問題中提供的所有信息,並自己重現你的問題嗎?如果不是,那麼你的問題不能滿足[mcve]的所有要求。 –

+0

好吧,你的'while'循環讀取3個標記並將它們傳遞給輸出文件。你爲什麼期望別的什麼東西在那裏?你提到**平均工資** - 你在哪裏計算它? – Fureeish

+0

您正在努力編寫任何信息。你有一個評論,說它有,但你沒有添加到該塊的代碼。如果你這樣做,你不會再有問題了。我們沒有爲你做功課。如果您希望在輸出中使用這些項目,請更改代碼以包含它們。 –

回答

0

你有什麼要做的就是用你的while循環語句中的一些條件和聲明(這是從文件中讀取)。每次循環執行時增加'numEmployee'變量(計數條目數)。

比較'w'讀取以檢查它是否低於minPay(初始化爲非常大的值)然後更新minPay否則如果高於maxPay(初始化爲最小值可能)更新maxPay。

此外,在循環中將'w'添加到另一個變量sumPay(初始化爲零),並在最後將其除以numEmployee,即可完成。 只需在return語句之前將它們輸出到文件中即可。

相關問題