As my term project to school, I wrote simple C application which calculates functional value of polynom, using Horner algoritm. One of the requests was to print the output to txt file. I solved it by some easy for cycle and fprintf functions.
My professor wants me to edit it to have united output to screen and to file via using library stdarg.h. I'm propably slightly retardet, becouse I have been trying to do it for three days without any result.
I have read most of the topics with similar theme, tried to implement some kinds of tee macro into it, but i was not capabble to make it work. Please, help me someone, or I will never pass this class by myself.
Whole code below
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#define OUT "./out.txt"
double horner(double * koe, int level, double x) {
int i;
for (i = level - 1; i >= 0; --i) {
koe[i] += x * koe[i + 1]; //
}
return koe[0];
} //poly[0]x(n-1) + poly[1]x(n-2) + .. + poly[n-1]
int scanINT() {
int number;
while (1) {
int LoadResult = scanf("%d", & number);
fflush(stdin);
if (LoadResult != 1) {
printf("Value is not number.\n");
} else {
return number;
}
}
return 0;
}
double ScanDouble() {
double number;
while (1) {
int LoadResult = scanf("%lf", & number);
fflush(stdin);
if (LoadResult != 1) {
printf("Value is not double.\n");
} else {
return number;
}
}
return 0;
}
int ScanPositiveNumber() {
while (1) {
int number = scanINT();
if (number < 0) {
printf("Value is negative.\n");
} else {
return number;
}
}
return 0;
}
int main(void) {
int level, i;
double x;
double * koe;
FILE * f = fopen(OUT, "w");
if (f == NULL) {
printf("Couldnt open file out.txt \n");
exit(1);
}
while (1) {
int option;
printf("********************************\n");
printf("Option 1: Functional value calc\n");
printf("Option 2: Save result and end\n");
printf("********************************\n\n");
option = scanINT();
if (option == 1) {
printf("Insert level of polynom: ");
level = ScanPositiveNumber();
koe = (double * ) malloc((level + 1) * sizeof(double));
if (koe == NULL) printf("Memory allocation failed.\n");
for (i = level; i >= 0; --i) {
printf("x^%d: ", i);
koe[i] = ScanDouble();
}
printf("Insert point x: ");
x = ScanDouble();
double hornerVal = horner(koe, level, x);
printf("f(%0.2f) = %0.2f\n", x, hornerVal);
for (i = level; i >= 0; --i) {
if (i != level) {
if (koe[i] < 0) {
fprintf(f, " ");
} else {
fprintf(f, " +");
}
}
fprintf(f, "%0.2fx^%d", koe[i], i);
}
fprintf(f, "\nf(%0.2f) = %0.2f\n", x, hornerVal);
free(koe);
} else if (option == 2) {
break;
}
}
if (fclose(f) != 0) {
printf("Couldnt save file out.txt \n");
}
return 0;
}
**/