2015-02-27 8 views
-1

Новое на C++, и у меня есть общий связанный список вопросов. Скажем, у меня есть:Общий связанный список C++

struct Node 
{ 
    string name; 
    Node *next 
}; 

в файле заголовка и у меня есть функция

Node ReadIntoList(const string INPUT_FILE) 
{ 
    ifstream inFile; 
    Node *head; 
    head = NULL; 
    Node *perPtr; 
    perPtr = new Node; 

    inFile.open(INPUT_FILE); 
    while(inFile && perPtr!= NULL) 
    { 
     getline(inFile, perPtr->name); 
     perPtr -> next = head; 
     head = perPtr; 
     perPtr = new Node; 
    } 
    delete perPtr; 
    perPtr = NULL; 

    return *head; 
} 

Мой вопрос: что мне нужно сделать, чтобы вернуться из функции ReadIntoList к основному , так что я могу получить доступ к списку а затем можно настроить функцию для вывода ее в файл. Вот мой основной до сих пор ...

int main() 
{ 
    ofstream oFile; 
    string inputFile; 
    Node *head; 

    cout << left; 
    cout << "Please enter the name of the input file you would like to " 
      "use: "; 

    getline(cin, inputFile); 

    head = ReadIntoList(inputFile); 

    oFile.open("OFile.txt"); 


    return 0; 
} 

Этот узел в основной не настроен правильно, очевидно, но я не уверен, как получить доступ к информации из ReadIntoList.

+1

Если вы действительно используете C++, вы должны использовать 'std :: list' или' std :: forward_list' вместо управления узлами вручную. –

+0

1. См. Ответ @RemyLebe выше. 2. Если по какой-либо причине (например, вы хотите реализовать свои собственные), вы можете просто вернуть 'head' в' ReadIntoList', и вы можете установить 'head' в свою основную часть из возвращаемого значения' ReadIntoList' –

+0

ответьте на свой конкретный вопрос, общий для простого списка вы можете обращаться с указателем головы как с дескриптором списка. так что вы должны вернуться. Но вы не показываете, что вы возвращаете в вопросе (код отключен). Эти удаления perPtr вызовов выглядят очень странно. Используйте std :: list, как сказали другие – pm100

ответ

4

В коде ReadIntoList() возвращается в содержание в последнего узла в списке (что приведет к сбою, если входной файл не открывается). ReadIntoList() необходимо вместо этого вернуть указатель на первый узел в списке. Это позволит main() цикл по списку, например:

Node* ReadIntoList(const string &inputFile) 
{ 
    ifstream inFile; 
    Node *head = NULL; 
    Node *last = NULL; 
    Node *perPtr = NULL; 

    inFile.open(inputFile); 
    if (inFile) 
    { 
     do 
     { 
      perPtr = new Node; 
      if (!getline(inFile, perPtr->name)) 
      { 
       delete perPtr; 
       break; 
      } 
      perPtr->next = NULL; 

      if (!head) head = perPtr; 
      if (last) last->next = perPtr; 
      last = perPtr; 
     } 
     while (true); 
    } 

    return head; 
} 

int main() 
{ 
    ofstream oFile; 
    string inputFile; 
    Node *head; 
    Node *perPtr; 
    Node *tmp; 

    cout << left; 
    cout << "Please enter the name of the input file you would like to use: "; 

    getline(cin, inputFile); 

    head = ReadIntoList(inputFile); 
    if (head) 
    {  
     oFile.open("OFile.txt"); 
     if (oFile) 
     { 
      perPtr = head; 
      do 
      { 
       oFile << perPtr->name << endl; 
       perPtr = perPtr->next; 
      } 
      while (perPtr != NULL); 
     } 

     perPtr = head; 
     do 
     { 
      tmp = perPtr->next; 
      delete perPtr; 
      perPtr = tmp; 
     } 
     while (perPtr != NULL); 
    } 

    return 0; 
} 

Это, как говорится, так как вы используете C++, вы должны использовать std::list (или std::forward_list в C++ 11 и позже), а, например:

#include <list> 

bool ReadIntoList(const string &inputFile, list<string> &outList) 
{ 
    outList.clear(); 

    ifstream inFile(inputFile); 
    if (!inFile) 
     return false; 

    string name; 
    while (getline(inFile, name)) 
     outList.push_back(name); 

    return true; 
} 

int main() 
{ 
    ofstream oFile; 
    string inputFile; 
    list<string> items; 

    cout << left; 
    cout << "Please enter the name of the input file you would like to use: "; 

    getline(cin, inputFile); 

    if (ReadIntoList(inputFile, items)) 
    { 
     oFile.open("OFile.txt"); 
     if (oFile) 
     { 
      for (list<string>::const_iterator iter = items.begin(), end = items.end(); iter != end; ++iter) 
      { 
       oFile << *iter << endl; 
      } 
     } 
    } 

    return 0; 
} 
+0

спасибо за помощь. Я думаю, что понимаю концепцию ... – Maclem

Смежные вопросы