Hi all,
I'm a beginner at C and I'm currently trying to input a string and 10 integers from a file, and then be able to sort them by the string in ascending order.
The file looks like this (first string is a place, the next 10 integers are distances)(random numbers I picked by the way :P)
London 0 23 12 89 456 123 46 732 345 123
Bath 23 0 46 234 123 46 89 234 567 90
The distances are relative to each other....
ie.. London to Bath would be 23 km, which can be read from column 2 on line 1 or first column on line 2
Now, I can easily input the files and print them using the below code (part of a function) and then using 2 for loops to print them out.
Code:
FILE *openFile;
char line[15];
char filename[16];
char rtn;
int i, j;
printf("Please enter the filename of the input file:");
gets(line);
sscanf(line,"%s%c\n", filename, &rtn);
openFile = fopen(filename, "r");
if (openFile == NULL)
{
puts("Error Opening File");
}
for (i = 0; i < 10; i++)
{
fscanf(openFile, "%s", &theArray2[i]);
for (j = 0; j < 10; j++)
{
fscanf(openFile, "%d", &theArray[i][j]);
}
}
}
Furthermore, I can easily sort the strings in ascending order by the following code:
Code:
int comp(const void *str1, const void *str2)
{
return strcmp(str1, str2);
}
void sortArray(char theArray2[10][11])
{
qsort(theArray2, 10, sizeof(theArray2[0]), comp);
}
BUT... I can't get the integers as described at the beginning of this thread to follow with the strings in order. I've tried using structs (like the one below) using fread in a for loop but i can't get that to work either!
Code:
typedef struct{
char places[10];
int distances[10];
}placedist;
I've tried a load of things... Just wondering what I can do to solve this problem!!
Hope you can help,
xfactor