我是C++的新手,正在为一个班级工作.我们获得了一个.txt文件,必须从中读取信息,并将其存储在链表中,然后将其打印给用户.经过几个小时的尝试操作我们给出的例子,再过几个小时尝试从头开始编写代码,我与两者的关系都变得最接近.
该文件名为payroll.txt,在这种格式中大约有30行:
Clark Kent 55000 2500 0.07
Lois Lane 65000 1000 0.06
Tony Stark 70000 1500 0.05
我们的教授非常重视我们的代码,所以我希望它有所帮助.这是我的代码:
#include <cstdlib>
#include <stdio.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
#define MAX_STR 100
/* Structure Definition */
typedef struct employeeType Employ;
struct employeeType {
char first[MAX_STR]; /* first name */
char last[MAX_STR]; /* last name */
int salary; /* salary */
int bonus; /* bonus */
double deduc; /* percent deduction */
Employ *next;
};
/* operations on the data */
Employ *ReadRecord();
void PrintRecord(Employ *);
main()
{{
Employ *head, *tail, *newp, *tmp;
head = tail = newp = tmp = NULL;
FILE *in; /* file description */
/* open a file, check if it's there */
if( (in = fopen( "payroll.txt", "r" )) == NULL )
{
printf( "Error opening file\n" );
exit(1);
}
while( newp = ReadRecord() )
{
/* Add object to the list */
if( head == NULL )
{
/* Beginning of the list */
head = newp;
/* Current record */
tail = newp;
}
else
{
/* Previous record reference to new record */
tail->next = newp;
/* Current record */
tail = newp;
}
}
/* End of the list */
tail->next = NULL;
/* Loop through the list */
for( tmp=head; tmp!=NULL; tmp=tmp->next )
{
PrintRecord( tmp );
}
Run Code Online (Sandbox Code Playgroud)
现在当我编译时,我得到错误:
[链接器错误]未定义引用ReadRecord()
[链接器错误]未定义引用PrintRecord(employeeType*)
我几乎可以肯定他在示例中给我们的ReadRecord和PrintRecord命令是伪代码意味着弄乱我们,但我不知道可以去那里.我一直在倾注多本教科书,并寻找一种简单的方法来在线修复链接器错误,并且已经没有想法了.
如果有人能帮助我/指出我正确的方向,将不胜感激.指向链接列表和链接器错误的更多信息的网页链接将更加精彩.
谢谢,
亚当
链接器抱怨你已经引用的函数ReadRecord和PrintRecord,但是你有没有写他们呢.您可以在当前文件的末尾编写这些函数.您可以从这个模板开始:
// Read a record from the file and parse the data into a structure
Employ *ReadRecord (void) {
// Use fgets() to read a line from the file
// Create a new Employ object to hold the data
// Use sscanf() to parse individual fields out of the string
// and store them in the new Employ object
// Return a pointer to the new Employ object
return (Employ*)NULL;
}
// Print the information from the structure to the screen
void PrintRecord (Employ *ptr) {
// Use printf() to display the content of each field
return;
}
Run Code Online (Sandbox Code Playgroud)
将这些函数模板添加到文件中后,链接器不应再抱怨未定义的引用(因为现在已经创建了函数).但是,代码将无法正常工作,因为这些函数实际上并没有执行任何操作.您需要填写函数正文(根据作业的详细信息).
编辑:我已经包含了一些提示(作为代码注释),以防你不知道从哪里开始.有关从文本文件解析数据或向屏幕显示信息的详细帮助,请参阅您的教科书(它应该有许多示例可以帮助您在此实例中).
更新:一些链接: