Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reads City - Temp pairs from file, sorts, and write out
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define MAX_TEMP 100
#define NAME_LEN 128
struct city_data{
char name[128];
int temp;
};
void xchg(struct city_data *left,struct city_data *right)
{
char name[NAME_LEN];
int temp;
strcpy(name,left->name);
temp=left->temp;
strcpy(left->name,right->name);
left->temp=right->temp;
strcpy(right->name,name);
right->temp=temp;
}
//left->temp == (*left).temp
int main(){
FILE *fr;
FILE *fw;
char row[255];
char *token;
unsigned n=0,min_index=0;
int i,changed=1;
struct city_data cd[MAX_TEMP];
fr = fopen("homerseklet.txt", "r");
while (fgets(row, 255, fr) != NULL) {
if ((strlen(row)>0) && (row[strlen (row) - 1] == '\n'))
row[strlen (row) - 1] = '\0';
token = strtok(row," ");
strcpy(cd[n].name, token);
token = strtok(NULL, " ");
cd[n].temp = atoi(token);
n++;
}
for(i=1;i<n;i++){
if(cd[i].temp<cd[min_index].temp){
min_index=i;
}
}
while(changed){
changed=0;
for(i=0;i<n-1;++i){
if(cd[i].temp>cd[i+1].temp){
changed=1;
xchg(&cd[i],&cd[i+1]);
}
}
}
fw = fopen("homerseklet_rendezett.txt", "w+");
for (i=0;i<n;++i){
fprintf(fw, "%s %i\n", cd[i].name,cd[i].temp);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment