2014-06-26 41 views
1

好的,我從未與fstream合作過,或者在程序中打開並讀取過文件。我的老師給了幾行代碼打開,閱讀和關閉一個文本文件。我應該從文本文件中取出數據並將其放入鏈表中的單獨節點,然後繼續使用它來做其他事情,這並不重要,因爲我知道該怎麼做。我的問題是,我不知道如何將這些值分配給結構值。將txt文件數據分配給鏈接列表中的結構節點

txt文件看起來是這樣的:

克拉克·肯特55000 2500 0.07

路易絲萊恩56000 1500 0.06

託尼·斯塔克34000 2000 0.05

...

我創建一個叫做Employee的結構,然後是基本插入函數,所以我可以將新節點添加到列表中。現在我該如何將這些名字和數字加入到我的結構中。

這裏是我的代碼:

#include <fstream> 
#include <iostream> 
using namespace std; 

struct Employee 
{ 
    string firstN; 
    string lastN; 
    float salary; 
    float bonus; 
    float deduction; 

    Employee *link; 
}; 

typedef Employee* EmployPtr; 
void insertAtHead(EmployPtr&, string, string, float, float,float); 
void insert(EmployPtr&, string, string, float, float,float); 

int main() 
{ 
    // Open file 
    fstream in("payroll.txt", ios::in); 

    // Read and prints lines 
    string first, last; 
    float salary, bonus, deduction; 

    while(in >> first >> last >> salary >> bonus >> deduction) 
    { 
     cout << "First, last, salary, bonus, ded: " << first << ", " << last << ", " << salary << ", " << bonus << ", " << deduction <<endl; 
    } 

    // Close file 
    in.close(); 

    EmployPtr head = new Employee; 


} 

void insertAtHead(EmployPtr& head, string firstValue, string lastValue, 
      float salaryValue, float bonusValue,float deductionValue) 
{ 
    EmployPtr tempPtr= new Employee; 

    tempPtr->firstN = firstValue; 
    tempPtr->lastN = lastValue; 
    tempPtr->salary = salaryValue; 
    tempPtr->bonus = bonusValue; 
    tempPtr->deduction = deductionValue; 

    tempPtr->link = head; 
    head = tempPtr; 
} 

void insert(EmployPtr& afterNode, string firstValue, string lastValue, 
     float salaryValue, float bonusValue,float deductionValue) 
{ 
    EmployPtr tempPtr= new Employee; 


    tempPtr->firstN = firstValue; 
    tempPtr->lastN = lastValue; 
    tempPtr->salary = salaryValue; 
    tempPtr->bonus = bonusValue; 
    tempPtr->deduction = deductionValue; 

    tempPtr->link = afterNode->link; 
    afterNode->link = tempPtr; 
} 

而且,我試圖尋找這一點,結果出來了,但他們都打開和讀取數據不同於我得到什麼。我是來自java的C++的新手,所以我不瞭解我有時看到的一些代碼。

+1

你的教師沒有介紹如何實例化對象嗎? –

+0

是的我知道如何實例化一個對象哈哈,我基本上只是不知道在while循環中發生了什麼。數據得到格式化和打印,但我不知道這是如何發生的,我真的沒有看到任何代碼將文本數據分配給這些變量首先,最後,薪水等等,以便打印它是如何。如果這有道理? – DomBavetta

回答

1
EmployPtr head = new Employee; 

while(in >> first >> last >> salary >> bonus >> deduction) 
{ 
    cout << "First, last, salary, bonus, ded: " << first << ", " << last << ", " << salary << ", " << bonus << ", " << deduction <<endl; 
    insertAtHead (head, first, last, salary, bonus, deduction); 
} 

您已有99%的解決方案。您只需在讀取文件時構建列表。

+0

謝謝,那是它!我只是不知道這些值已經被分配給了某些東西。 – DomBavetta

相關問題