gpt4 book ai didi

c++ - 将txt文件数据赋值给链表中的struct节点

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:49 24 4
gpt4 key购买 nike

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

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++ 新手,所以我不理解我有时看到的一些代码。

最佳答案

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

关于c++ - 将txt文件数据赋值给链表中的struct节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24439935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com