I have a file with fractions. I have to write fractions from it into a structure. Then I need to create a dynamic data structure in order to add those fractions that have a common denominator, but I should not use dynamic arrays. Can you please help me with the fraction addition part? (the link contains a photo of the file with fractions and the result I want to get, but for now I can only display fractions on the screen, but not add them up) enter image description here
#include <iostream>
#include <stdio.h>
#include <Windows.h>
#include <string.h>
using namespace std;
struct fraction {
int numerator, denominator;
};
struct Node {
fraction fr;
Node* next;
};
Node* newNode(fraction fr) {
Node* p;
p = new Node;
p->fr.numerator = fr.numerator;
p->fr.denominator = fr.denominator;
p->next = NULL;
return p;
}
void addNode(Node* curr, Node** head, Node** tail) {
if (*head == NULL) {
*head = *tail = curr;
// *tail = curr;
}
else {
(*tail)->next = curr;
*tail = curr;
}
}
void outList(Node* head) {
Node* curr;
curr = head;
while (curr != NULL) {
cout << curr->fr.numerator << "/" << curr->fr.denominator << endl;;
curr = curr->next;
}
}
int main() {
fraction fr;
int n;
Node* curr = NULL;
Node* head = NULL;
Node* tail = NULL;
FILE* f;
fopen_s(&f, "testfile.txt", "r");
if (f) {
while (!feof(f)) {
fscanf_s(f, "%d", &n);
for (int i = 0; i < n; i++) {
fscanf_s(f, "%d", &fr.numerator);
fscanf_s(f, "%d", &fr.denominator);
curr = newNode(fr);
addNode(curr, &head, &tail);
}
}
fclose(f);
outList(head);
}
}