So I'm slowly continuing learning C. And now, I have a task, to read data from a file and sort it.
File data:
House naming 1 30 300
House naming 2 45 450
.......
House naming 10 5 120
So, first value: House naming
, can be any naming like Empire state building
The second value is: House address (I chose only integer
values)
The third value is: Age of a building
The fourth value is: Kilowatt-hour/year
Programm must take data from a file -> Print it out -> Sort(how? see below) -> print out again, sorted.
Sorting:
- kwh < 200 - sustainable building,
- kwh < 300 && age < 40 - needs renovation,
- kwh > 300 && age > 40 - set for demolition.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include "input.h"
int main(void) {
int kwh;
int age;
char building[SIZE];
int addr;
char buff[SIZE];
FILE *fi;
// opening the files and checking if it succeeded
fi = fopen(F_INPUT, "r");
if (fi == NULL) {
printf("Error opening input file \"%s\"", F_INPUT);
exit(EXIT_INPUT_FAIL);
}
while (fgets(buff, sizeof(buff), fi) != NULL) {
sscanf(buff, "%s %d %d %d", building, &addr,&age,&kwh);
if (kwh < 200) {
puts(buff);
printf("Sustainable\n");
} else
if (kwh < 300 && age < 40) {
puts(buff);
printf("Needs renovation\n");
} else
if (kwh > 300 && age > 40) {
puts(buff);
printf("IN DEMOLITION LIST\n");
}
}
/* close the files when they're not needed anymore */
fclose(fi);
return 0;
}
I've combined a few steps to make it a bit easier, reads data -> outputs already marked 1) Sustainable, 2) Needs renovation, 3) set for demolition.
The problem is somewhere in the while
loop and I think it's in sscanf
function.
In my logic, if I am not mistaken, it must read a string from a file, using logic(look at sscanf
and input file): char value
, integer
, integer
, integer
.
Programm reads the file, outputs the data, but marks all buildings as sustainable
.
What you suggest to read more carefully or what logic is better to choose for reading multiple strings.
Output:
House naming 1 30 300
Sustainable
House naming 2 45 450
Sustainable
........
House naming 10 5 120
Sustainable