Witam serdecznie, jestem początkującym programistą i mam niemały problem z programem, który ma za zadanie dokonać dodawania dwóch liczb, podanych w dwóch plikach tekstowych. Implementacja ma wykorzystywać 3 stosy. Niestety program, który napisałem nie wykonuje przeniesienia przy dodawaniu, a także przestaje działać przy próbie zapisania wyniku do pliku tekstowego. Prosiłbym też o rady dotyczące poprawy jakości mojego kodu, gdyż z każdego napisanego programu chciałbym wynieść jak najwięcej. Z góry serdecznie dziękuję i pozdrawiam :)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct STOS
{
int key;
struct STOS *next;
}
;
void push(struct STOS **Head, int x)
{
struct STOS *newHead=NULL;
newHead=(struct STOS*)malloc(sizeof(struct STOS));
newHead->key=x;
newHead->next=*Head;
*Head=newHead;
printf("Umieszczono %d na stosie\n", x);
}
void pop(struct STOS **Head)
{
if(Head==NULL) printf("Stos jest pusty!");
struct STOS *temporaryHead=*Head;
*Head=temporaryHead->next;
free(temporaryHead);
}
void zapisz(int dana, struct STOS **head)
{
printf("\nZapisuje...\n");
int zapis;
if((dana%10)==0) push(head, dana);
else
{
while((dana % 10) != 0)
{
zapis = (dana % 10);
push(head,zapis);
dana = (dana/10);
}
}
}
void przepisz(struct STOS *headStary, struct STOS **headNowy)
{
printf("\nPrzepisuje...\n");
int klucz;
while(headStary)
{
klucz = (headStary -> key);
push(headNowy, klucz);
headStary=headStary->next;
}
}
void sumuj(struct STOS *head1,struct STOS *head2,struct STOS **headWynik)
{
while(head1 != NULL || head2 != NULL)
{
int suma = 0;
if( head1 != NULL )
{
suma += head1 -> key;
head1 = head1 -> next;
}
if( head2 != NULL )
{
suma += head2 -> key;
head2 = head2 -> next;
}
push( headWynik, suma );
}
}
int main()
{
struct STOS *head1start = NULL;
struct STOS *head2start = NULL;
struct STOS *head1nowy = NULL;
struct STOS *head2nowy = NULL;
struct STOS *headWynik = NULL;
FILE *fp ;
fp = fopen("in_1.txt", "r");
if(fp == NULL)
{
perror("Nie udalo sie otworzyc pliku in_1.txt");
return 1;
}
FILE *fs;
fs = fopen("in_2.txt", "r");
if(fs == NULL)
{
perror("Nie udalo sie otworzyc pliku in_2.txt");
return 2;
}
FILE *ft;
ft = fopen("wynik.txt", "w");
if(ft == NULL)
{
perror("Nie udalo sie otworzyc pliku wynik.txt");
return 3;
}
char pierwsza[1000000], *result1;
char druga[1000000], *result2;
result1 = fgets(pierwsza, 1000000, fp);
result2 = fgets(druga, 1000000, fs);
int a = atoi(result1);
int b = atoi(result2);
zapisz(a, &head1start);
zapisz(b, &head2start);
przepisz(head1start, &head1nowy);
przepisz(head2start, &head2nowy);
sumuj(head1nowy, head2nowy, &headWynik);
printf("\nSuma podanych liczb wynosi:\n");
while(headWynik)
{
printf("%d", headWynik -> key);
char wynikowa[1000000], *ostateczna;
sprintf(ostateczna, "%d", headWynik);
fprintf(ft, "%s", ostateczna);
fclose(ft);
headWynik = headWynik -> next;
}
printf("\n");
system("PAUSE");
return 0;
}