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
%sstops at the first whitespace, so it can't be used to read, as your example, "Empire state building". One solution could be to break the input string into an array of token pointers withstrtok, extract integers from the last three, and build a new string from the first ones remaining.sscanfis not working as you expect it to. Always check the return values of functions, in this casesscanf. And invest time into learning how to use a debugger. Also useful: How to debug small programs"Saturday Sunday March 25 1989"it would not work properly. Format%sstops at the first whitespace. The best thing you can do IMO is to write a short test program to explore howscanfbehaves, and with no other purpose.