|
-
April 27th, 2004, 02:43 PM
#1
storing in text file
Hi,
I'm having some problems storing data to a text file. I have created a program that creates linked lists, but i now need to take this list and save it to a text file. I cant seem to be able to get it to work.
Eventually i would like to be able to retrieve the data from a file and store it in a linked list but thats another problem.
Hope someone can help.
The code I have developed so far is shown below:
#include <iostream.h>
struct node
{
char first_name[30];
char last_name[30];
int age;
node *nxt;
};
node *start_ptr = NULL;
node *current; // Used to move along the list
int option = 0;
void add_node_at_end ()
{ node *temp, *temp2; // Temporary pointers
// Reserve space for new node and fill it with data
temp = new node;
cout << "Please enter the name of the person: ";
cin >> temp->first_name;
cout << "Please enter the age of the person : ";
cin >> temp->age;
cout << "Please enter the surname of the person : ";
cin >> temp->last_name;
temp->nxt = NULL;
// Set up link to this node
if (start_ptr == NULL)
start_ptr = temp;
else
{ temp2 = start_ptr;
// We know this is not NULL - list not empty!
while (temp2->nxt != NULL)
{ temp2 = temp2->nxt;
// Move to next link in chain
}
temp2->nxt = temp;
}
}
void display_list()
{ node *temp;
temp = start_ptr;
cout << endl;
if (temp == NULL)
cout << "The list is empty!" << endl;
else
{ while (temp != NULL)
{ // Display details for what temp points to
cout << "Name : " << temp->first_name << " ";
cout << "Age : " << temp->age << " ";
cout << "Surname : " << temp->last_name;
if (temp == current)
cout << " <-- Current node";
cout << endl;
temp = temp->nxt;
}
cout << "End of list!" << endl;
}
}
void main()
{
start_ptr = NULL;
do
{
cout << endl;
cout << "Please select an option : " << endl;
cout << "0. Exit the program." << endl;
cout << "1. Add a node to the end of the list." << endl;
cout << "2. Display List of nodes. " << endl;
cout << endl << " >> ";
cin >> option;
switch (option)
{
case 1 : add_node_at_end();break;
case 2 : display_list();
}
}
while (option != 0);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|