Hi,
I want to swap all the strings around in my array that have come from a file so they're in ascending order.
The .txt file is:
341949 English 7
487476 English 83
528191 English 59
003953 English 88
075160 English 34
713494 English 42
765251 English 40
400683 English 52
843007 English 71
421311 English 47
421311 Mathematics 52
580313 English 91
580313 Mathematics 97
421311 Physics 74
223170 English 81
131782 English 51
421311 Computing 11
528191 Mathematics 85
886030 English 84
832912 English 94
003953 Mathematics 29
073241 English 99
131782 Mathematics 59
075160 Mathematics 92
580313 Physics 63
073241 Mathematics 32
487476 Mathematics 73
075160 Physics 98
472832 English 44
713494 Mathematics 0
400683 Mathematics 72
765251 Mathematics 27
599828 English 11
713494 Physics 48
223170 Mathematics 49
580313 Computing 78
765251 Physics 42
843007 Mathematics 48
487476 Physics 85
832912 Mathematics 62
832912 Physics 72
223170 Physics 54
341949 Mathematics 45
487476 Computing 76
886030 Mathematics 20
868717 English 2
223170 Computing 72
868717 Mathematics 37
659183 English 57
659183 Mathematics 67
528191 Physics 8
341949 Physics 48
843007 Physics 40
341949 Computing 41
472832 Mathematics 88
472832 Physics 91
472832 Computing 95
131782 Physics 97
073241 Physics 73
528191 Computing 49
868717 Physics 49
886030 Physics 39
075160 Computing 80
599828 Mathematics 57
400683 Physics 57
400683 Computing 16
659183 Physics 65
073241 Computing 63
713494 Computing 38
886030 Computing 25
843007 Computing 98
868717 Computing 15
832912 Computing 63
003953 Physics 83
131782 Computing 38
765251 Computing 95
659183 Computing 22
003953 Computing 38
599828 Physics 99
599828 Computing 86
My program successfully uses fgets() and then prints the strings back to the screen just to demonstrate the strings have been stored, but now I want to arrange these strings in an order like this:
341949 Computing 41
341949 English 7
341949 Mathematics 45
341949 Physics 48
And then print them on the screen to show it works so can write them to a file so all the student IDS are in some kind of ascending order with their subject and mark next to each ID.
If you look at my code I think the problem is with my swap function. I'm not sure what the parameters would be when I'm swapping strings as opposed towards elements of an array.
Code:#include <stdio.h> #include <string.h> #define LENGTH 23 #define LINES 80 void swap( char *x, char *y) { char temp=*x; *x=*y; *y=temp; } int main(void) { int i=0,j,k; FILE *input_file; char file[LENGTH]; char string[LINES][LENGTH]; if((input_file=fopen("C:\\file\\file.txt", "r"))==NULL) perror("File open failed"); else { while(fgets(file, LENGTH, input_file)!=NULL) { strcpy(string[i], file); i++; printf("%s", string[i]); } } for(j=0; j<LINES; j++) { for(k=0; k<LINES; k++) { if(strcmp(string[k],string[j])>0) swap(string[j], string[k]); } } return 0; }