我在大学的实验室任务之一是从* .txt文件中读取名称到链接的结构列表中,然后将列表传递给将名称打印到屏幕上的函数。这个问题似乎是我分配了指针的值并将其传递给我的函数的地方。如果有人能指出我要出错的地方,我将不胜感激。链接列表定义分配C++
person.h:
#ifndef PERSON_H
#define PERSON_H
#include<string>
#include<fstream>
#include<iostream>
using namespace std;
struct Person
{
Person *next;
string name;
};
void walklist(Person *head_Ptr);
#endif PERSON_H
person.cpp:
#include "person.h"
void walklist(Person*head_Ptr)
{
Person *cur;
for (cur = head_Ptr; cur!=NULL; cur=cur->next)
{
cout<< cur->name<<endl;
}
}
的main.cpp
#include<string>
#include<fstream>
#include<iostream>
#include"person.h"
using namespace std;
int main()
{
string myfilename, names_in;
cout<<"Please enter the name of the file to open";
cin>>myfilename;
fstream infile;
infile.open(myfilename.c_str());
if(infile.bad())
{
cerr<<"There has been a problem opening the file"<<endl;
system("PAUSE");
return -1;
}
Person *head_Ptr = NULL, *last_Ptr = NULL, *temp_Ptr;
while(infile.good())
{
getline(infile, names_in);
temp_Ptr = new Person;
temp_Ptr->name = names_in;
temp_Ptr->next = head_Ptr;
if(last_Ptr != NULL)
{
last_Ptr->next = temp_Ptr;
}
if(head_Ptr==NULL)
{
head_Ptr = last_Ptr;
}
}
walklist(head_Ptr);
system("Pause");
return 0;
}
什么是错误?它打印错了吗? – Stefan
使用'using namespace std;'不是一个好主意。 http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice –
与调试器一步一步地运行代码,你会很容易看到你的问题 –