2016-01-31 122 views
-4

我在大学的实验室任务之一是从* .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; 
} 
+1

什么是错误?它打印错了吗? – Stefan

+0

使用'using namespace std;'不是一个好主意。 http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice –

+2

与调试器一步一步地运行代码,你会很容易看到你的问题 –

回答

2

它不应该是

temp_Ptr->next = nullptr; // temp_Ptr will be the new last element 
           // so make sure that its next points to null 

    if(last_Ptr != NULL) 
    { 
     last_Ptr->next = temp_Ptr; // Update next pointer of the current last 
            // element to point to the new last element 
    } 

    last_Ptr = temp_Ptr;   // Update last to be the new element 

    if(head_Ptr==NULL) 
    { 
     head_Ptr = temp_Ptr;  // Update head if needed (i.e. when null) 
    } 
+0

你只是打败了我:-)尽管我不确定OP是否想要一个通告列表。 – Stefan

+0

@Stefan - 感谢您发布相同的答案:-)不幸的是,许多SO用户都这么做。甚至几分钟后。无论如何 - 关于“圆形列表”,我认为这是一个bug,因为“walklist”在目前的形式中存在问题。 – 4386427

+0

你们真棒!这是我整年无法做到的唯一实验室,它正在毁掉我的灵魂!它!它完美地工作,你甚至评论了代码。谢谢你,一群男子。 – J0rdy

0

似乎你是在正确的轨道上。该错误是在此代码:

if(last_Ptr != NULL) 
    { 
     last_Ptr->next = temp_Ptr; 
    } 
    if(head_Ptr==NULL) 
    { 
     head_Ptr = last_Ptr; 
    } 

第一次来到这里,既last_Ptrhead_Ptr为空。因此,您跳过第一个作业,但将last_Ptr指定为head_Ptr。然后他们仍然是NULL

+0

然后我会做什么呢? – J0rdy

+0

你不会在任何地方设置'last_Ptr'。也许在添加第一个节点时,'last_Ptr'和'head_Ptr'应该是相同的? –