Originally Posted by
Structure
What are you talking about???
@Tricica, all you need to do is read all the records into an array of structs and then sort the array. Note that you have not shown a numeric sort on the numbers, but an alphabetical sort. And the second number is always 0 in your examples. So if that's correct, you can do it like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RECORDS 100
typedef struct {
char type[10];
char x[10];
} Record;
int cmp_r(const void *a, const void *b) {
Record *ra = (Record*)a, *rb = (Record*)b;
int cmp = strcmp(ra->type, rb->type);
return cmp ? cmp : strcmp(ra->x, rb->x);
}
int main() {
FILE *fin = fopen("input.txt", "r");
Record r[MAX_RECORDS];
int n = 0;
Record in;
while (fscanf(fin, " %9[^[][%9[^,],%*d]", in.type, in.x) == 2) {
if (n >= MAX_RECORDS) {
fprintf(stderr, "Record array overflow.\n");
break;
}
strcpy(r[n].type, in.type);
strcpy(r[n].x, in.x);
++n;
}
qsort(r, n, sizeof *r, cmp_r);
for (int i = 0; i < n; ++i)
printf("%s[%s,0]\n", r[i].type, r[i].x);
return 0;
}
If sanity prevails and it really is a numeric sort for the numbers, and the second number is not always 0, then something like the following. This example is also more robust in terms of the spacing.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LINE 256
#define MAX_RECORDS 200
typedef struct {
char type[8];
int x, y;
} Record;
int cmp_r(const void *a, const void *b) {
Record *ra = (Record*)a, *rb = (Record*)b;
int cmp = strcmp(ra->type, rb->type);
if (cmp) return cmp;
cmp = ra->x - rb->x;
if (cmp) return cmp;
return ra->y - rb->y;
}
int main() {
FILE *fin = fopen("input.txt", "r");
Record r[MAX_RECORDS];
int n = 0;
for (char line[MAX_LINE]; fgets(line, sizeof line, fin) != NULL; ) {
Record in;
if (sscanf(line, " %7[^[][%d ,%d ]", in.type, &in.x, &in.y) != 3)
continue;
if (n >= MAX_RECORDS) {
fprintf(stderr, "Record array overflow.\n");
break;
}
// strip space from end
size_t len = strlen(in.type);
while (len && isspace(in.type[len - 1])) --len;
in.type[len] = '\0';
r[n++] = in;
}
qsort(r, n, sizeof *r, cmp_r);
for (int i = 0; i < n; ++i)
printf("%s[%d,%d]\n", r[i].type, r[i].x, r[i].y);
return 0;
}
Example input:
Code:
Au[10,1]
Al[12,2]
Au [ 11 , 1 ]
Au[2,1]
Al[5,1]
Au[10,0]
Al[0,0]
Au[0,0]
Al[5,0]
Al [ 0 , 1 ]
Au[12,0]
Al[10,1]
Au [ 10 , 2 ]
Al[10,0]
Al[12,0]
Al[1,0]
Au[11,0]
Au[2,0]
Al[12 , 1]
Al[0,2]
Au[2,2]
Au[2,3]
Au[4,0]