工资单计算器C ++中的链接列表

时间:2014-07-08 13:15:52

标签: c++ segmentation-fault

我必须为一个班级写一个工资单计算器程序,我遇到了一些问题。教师希望我们使用链接的结构列表来对数据对象的集合执行操作。

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>

using namespace std;

struct Employee
{
char *fname, *lname;
double salary, bonus, deduction_percent, Deduction, Net_sal;
Employee *next;
};

int main()
{
char line[1024];
char *first, *last, *salchar, *bonuschar, *deductionchar;
double sal, bonus, deduction;
Employee *head = NULL, *tail, *newp, *curr;
tail = NULL;
newp = NULL;
curr = NULL;
cout<<"hi"<<endl;
fstream myfile ("payroll.txt", ios::in) ;

if (myfile.is_open())
{
    //we want our head to point to the first employee, so we
    //must make our first employee before we iterate
    while ( myfile.good() )
    {
        myfile.getline(line,1024);
        //reads the txt file
        first = strtok (line, " ");
        last = strtok (NULL, " ");
        salchar = strtok (NULL, " ");
        bonuschar = strtok (NULL, " ");
        deductionchar = strtok (NULL, " ");

        sal = atof(salchar);
        bonus = atof(bonuschar);
        deduction = atof(deductionchar);

        newp = new Employee;
        newp->fname = first;
        newp->lname = last;
        newp->salary = sal;
        newp->bonus = bonus;
        newp->deduction_percent = deduction;
        newp->next = NULL;

        if(head == NULL)
        {
            head = newp;

            tail = newp;
        }
        else
        {
            tail->next = newp;
            tail = newp;
        }

这是我遇到问题的地方。当我编译程序时,我得到一个分段错误,在整个代码中放入一系列cout语句后,我发现问题在于这个循环。我想知道是否有更好的方法来读取我的文件,或者是否存在阻止循环工作的语法错误。

    myfile.close();  
}
for (curr=head; curr != NULL;curr=curr->next)
{
    cout<<curr->fname << " " <<curr->lname <<" "<< curr->salary<<" "<<curr->bonus<<" "<<curr->deduction_percent<<endl;
    curr = curr->next;
}
curr = head;
newp = head;
while (curr != NULL)
{
    curr->Deduction = (curr->salary + curr->bonus) * curr->deduction_percent;
    curr->Net_sal = (curr->salary + curr->bonus) - curr->Deduction;
}

//delete all the dynamic memory in the program
curr = head;
newp = head;
while (curr != NULL)
{
    curr = curr->next;
    delete newp;
    newp = curr;
}

}

1 个答案:

答案 0 :(得分:0)

如果您正在寻找更好的方式来阅读文件,我强烈建议您使用字符串流(http://www.cplusplus.com/reference/sstream/stringstream/)来表示空格之间的子串。我的代码并不靠近我的电脑,所以我无法给你一个很好的例子,但你可以将字符串流和getlines链接在一起并读取直到文件末尾。如果你正在使用Netbeans / Visual Studios寻找调试器并设置一些断点并逐步完成它,那就是我如何解决了很多处理链表/文件流的问题。