I'm having a issue with my code, it compiles and works but it skips the while loop entirely. The program uses a linked list also which I left out since my assumption would be that its the way I pass my pointers to functions is wrong?
struct node
{
string empName;
int empSal;
node *next;
};
void print(struct node* root, int average)
{
cout<<"The average of salaries is: $"<<average<<" !"<<endl;
node *current;
current = root;
while(current->next != 0)
{
cout<<"Name:"<<current->empName<<endl;
cout<<"Salary: $"<<current->empSal<<endl;
}
}
void average(struct node* root, int total)
{
int average=0;
int sum=0;
node *current;
current = root;
cout << "average" << endl;
while(current->next != 0) //this is the loop that it skips
{
cout << current->empSal<<endl;
sum= sum + current->empSal;
cout << sum << endl;
current = current->next;
}
average=sum/total;
print(root,average);
return;
}
@LendraDwi
Don't take this personally or anything but in C++ changing 0 to NULL would make literally no difference whatsoever. In C++ the definition for NULL is this: #define NULL 0 .
@Celtic222
The only reason I can think of that would cause the loop to skip would be that the 'next' pointer doesn't actually point to anything. Or at least it doesn't point to any memory location. I can't see anywhere in the code where you're actually setting the 'next' pointer in the structure any kind of memory location. I admit I could be wrong but we can't see the code where you're setting that pointer, so I'm just guessing.
void input()
{
int s=0; //defined and declared variable s (for salary)
int total=0;//defined and declared variable
string n; //declared variable n (for name)
node *current; //declared pointer current
node *root; //declared pointer root
node *temp; //declared pointer temp
root = new node; //creates a new node
root->next=0; //node is equal to 0
current = root; //current is now pointing to root
cout<<"Enter employee's name: "<<endl;
cin>>n;//user input name
cout<<"Enter employee's salary: "<<endl;
cin>>s;//user input salary
while(n != "z")//while loop used to create the linked list of employee names and salaries.
{
total++;//total=total+1
current->empName=n;//saving current name to variable n
current->empSal=s;
cout << current->empName << " " << current->empSal << endl;
temp = new node; //creates a new node
current->next = temp;//current is now pointing to temp
current->next = 0;
cout << current->empName << " " << current->empSal << endl;
cin>>n;
cin>>s;
}
average(root,total);
}
@Tom56785
This is the linked list that I have, calling the pointers, etc. So you're saying something is wrong in the input function on?