好的,所以我以前从未使用过fstream或在程序中打开和读取和文件。我的老师只是给了几行打开、读取和关闭文本文件的代码。我应该把数据从文本文件中取出并放到一个链表中单独的节点中然后继续对它做其他事情这并不重要,因为我知道怎么做。我的问题是我不知道如何将这些值赋值给结构体值。
文本文件看起来像这样:
克拉克肯特55000 2500 0.07
Lois Lane 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;
}
另外,我试过搜索这个和结果已经出现,但他们都打开并读取数据不同于我给出的。
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%的解决方案了。您只需要在读取文件时构建列表。