将txt文件数据分配给链表中的struct节点

时间:2014-06-26 20:47:04

标签: c++ linked-list nodes fstream assign

好的,所以我以前从未使用过fstream,也没有在程序中打开和读取文件。我的讲师只给了几行打开,读取和关闭文本文件的代码。我应该从文本文件中取出数据并将其放入链表中的单独节点中,然后继续用它做其他事情,这并不重要,因为我知道如何做到这一点。我的问题是我不知道如何将这些值分配给struct值。

txt文件如下所示:

Clark Kent 55000 2500 0.07

Lois Lane 56000 1500 0.06

Tony Stark 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 :(得分: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%的解决方案。您只需在阅读文件时构建列表。