Hi, I'm doing this exercise that should print a list containing the differences between two integers x and y, here the code:
The problem is that if I want to break the loop I have to enter the EOF character (ctrl+d) 2 times while it should be entered only once, and the last element of the list gets printed twice, I think there are some issues with the getchar() function but I can't figure out what.. any help? thanksCode:#include <stdio.h>
#include <stdlib.h>
struct node {
int diff;
struct node* next;
};
typedef struct node Node;
void Push(Node** headRef, int data)
{
Node* newNode = malloc(sizeof(Node));
newNode->diff = data;
newNode->next = *headRef;
*headRef = newNode;
}
void printList(Node** headRef)
{
Node* current = *headRef;
while(current!=NULL) {
printf("%d\n", current->diff);
current = current->next;
}
}
int main()
{
int x, y, diff;
Node* head = NULL;
Node* tail;
scanf("%d%d", &x, &y);
diff = y-x;
Push(&head, diff);
tail = head;
while(getchar()!=EOF) { // <---- getchar() function..
scanf("%d%d", &x, &y);
diff = y-x;
Push(&(tail->next), diff);
tail = tail->next;
}
printList(&head);
return 0;
}