Help with C++, linked lists
Hi guys,
I'm trying to write a program that stores a name, ID number, average test score, and letter grade for up to 20 students. This code here will only store/print one student's information. I can't figure out how to get it to store more than that. Any advice?
Code:
#include <iostream>
using namespace std;
struct node
{ char name[20]; // Name of up to 20 letters
int idNum;
int avgScore[20];
char grade[20];
node *nxt; // Pointer to next node
};
node *start_ptr = NULL;
node *current; // Used to move along the list
int option = 0;
void add_record()
{ node *temp, *temp2; // Temporary pointers
//node avgScore;
// Reserve space for new node and fill it with data
int* a = NULL; // Pointer to int, initialize to nothing.
int n; // Size needed for array
cout << "\n\t--------------Student Information---------------\n";
cout << "How many test scores this semester? ";
cin >> n; // Read in the size
a = new int[n]; // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++)
{
a[i] = 0; // Initialize all elements to zero.
}
int m;
cout << "How many students in the course? ";
cin >> m;
temp = new node;
for (int k=0; k<m; k++)
{
cout << "Please enter the name of student " << (k+1) << ": ";
cin >> temp->name;
cout << "Please enter the ID Number of the student : ";
cin >> temp->idNum;
cout << "Please enter student's test scores for the " << n << " tests: ";
for (int j=0; j<n; j++)
{
cout << "\nTest " << (j+1) << ": ";
cin >> a[j];
/*for (int p=0; p<j; p++)
{
temp->avgScore = (temp->avgScore + a[p]) / p;
}*/
}
}
temp->nxt = NULL;
// Set up link to this node
if (start_ptr == NULL)
{ start_ptr = temp;
current = start_ptr;
}
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 << "List currently empty." << endl;
else
{ while (temp != NULL)
{ // Display details for what temp points to
cout << "Name : " << temp->name << " ";
cout << "idNum : " << temp->idNum << " ";
cout << "avgScore : " << temp->avgScore;
if (temp == current)
cout << " <-- Current node";
cout << endl;
temp = temp->nxt;
}
cout << "End of list!" << endl;
}
}
void main()
{ start_ptr = NULL;
do
{
display_list();
cout << endl;
cout << "Please select an option : " << endl;
cout << "1. Create new record." << endl;
cout << "2. Exit the program." << endl;
cin >> option;
switch (option)
{
case 1 : add_record(); break;
}
}
while (option != 2);
}
I know not all the steps are there for everything, my main concern is how to get it to store/print more than one student. I appreciate any responses.
Thanks!