insert file data to linked list?

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Jun 2008
Posts: 92
Reputation: JackDurden is an unknown quantity at this point 
Solved Threads: 0
JackDurden JackDurden is offline Offline
Junior Poster in Training

insert file data to linked list?

 
0
  #1
Oct 2nd, 2008
How do I get the data from file into the Insert function? Or more general how do you get data from a file and put it into a linked list?

  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. class List
  7. {
  8. public:
  9. void Insert();
  10. void Print();
  11. };
  12.  
  13. struct node
  14. {
  15. int age;
  16. node *nxt;
  17. };
  18. node *start_ptr = 0;
  19. node *current;
  20.  
  21. void List::Insert()
  22. { node *temp, *temp2; // Temporary pointers
  23.  
  24. // Reserve space for new node and fill it with data
  25. temp = new node;
  26. temp->age;
  27.  
  28. temp->nxt = NULL;
  29.  
  30. // Set up link to this node
  31. if (start_ptr == NULL)
  32. { start_ptr = temp;
  33. current = start_ptr;
  34. }
  35. else
  36. { temp2 = start_ptr;
  37. // We know this is not NULL - list not empty!
  38. while (temp2->nxt != NULL)
  39. { temp2 = temp2->nxt;
  40. // Move to next link in chain
  41. }
  42. temp2->nxt = temp;
  43. }
  44. }
  45. void List::Print()
  46. { node *temp;
  47. temp = start_ptr;
  48.  
  49. if (temp == NULL)
  50. cout << "The list is empty" << endl;
  51. else
  52. { while (temp != NULL)
  53. { // Display details for what temp points to
  54. cout << "Age : " << temp->age << " ";
  55.  
  56. if (temp == current)
  57. cout << " <-- Current node";
  58. cout << endl;
  59. temp = temp->nxt;
  60.  
  61. }
  62. cout << "End of list!" << endl;
  63. }
  64. }
  65. void main()
  66. {
  67. start_ptr = NULL;
  68. List display;
  69. fstream inFile;
  70. node number;
  71. inFile.open("int.txt");
  72.  
  73. inFile>>number.age;
  74.  
  75. display.Print();
  76. display.Insert();
  77.  
  78. }
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC