I have created a program in c to read the temperature of a specific number of days, and then save all the data inputed into an XML file. I have handled to code the program, and make it generate an XML file with the data inputed in it, however the output displayed in the XML file is wrong, it is somehow badly formatted, so I would like to know if someone could help me with it, it is the first time I am working with XML.
My code is basically this:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
double minimum;
double maximum;
double average;
int daynumber;
}Measurement;
#define QUANT 31
void measure(Measurement *);
void output(FILE *, Measurement *);
int main(int argc, char** argv) {
Measurement m[QUANT];
int i;
FILE *f;
printf("Input data:\n");
for(i=0; i<1; i++)
measure(&m[i]);
printf("\nData was saved into xml file\n");
f = fopen("data.xml","w");
if(f==NULL){
printf("Error");
return 0;
}
fprintf (f,"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
for(i=0;i<1;i++){
output(f,m);
}
fclose(f);
return (EXIT_SUCCESS);
}
void measure(Measurement *x){
printf("Input minimum temperature: ");
scanf("%f",&x->minimum);
printf("Input maximum temperature: ");
scanf("%f",&x->maximum);
printf("Input average temperature: ");
scanf("%f",&x->average);
printf("Input day number: ");
scanf("%f",&x->daynumber);
}
void output(FILE *f, Measurement *x){
fprintf(f,"<day>\n");
fprintf(f,"<minimum>%f</minimum>\n",x->minimum);
fprintf(f,"<maximum>%f</maximum>\n",x->maximum);
fprintf(f,"<average>%f</average>\n",x->average);
fprintf(f,"<daynumber>%d</daynumber>\n",x->daynumber);
fprintf(f,"</day>\n");
}
My output then is always like this:
<?xml version="1.0" encoding="utf-8"?>
<day>
<minimum>0.000000</minimum>
<maximum>0.000000</maximum>
<average>0.000000</average>
<daynumber>1065353216</daynumber>
</day>
Could you see what may be wrong in my code? Thanks in advance.
output()always accessm[0].printf("Error");1) error messages should be output tostderr, notstdout. 2) when the errorscanf("%f",&x->average); is from a C library function, should also output (tostderr) the text reason the system thinks thscanf("%f",&x->average);e error occurred. The functionperror()is made to handle this scenario. Suggest:perror( "fopen failed" );scanf("%f",&x->average);when calling any of thescanf()family of functions, always check the returned value (not the parameter values) In the current scenario, suggest:if( scanf("%f",&x->average) != 1 ) { fprintf( stderr, "failed to read average\n" ); exit( EXIT_FAILURE ); }