我目前正在尝试对我的“grades.csv”文件(excel)使用插入排序。我将grades.csv放入一个名为char line []的字符串数组中。文件内包含:StudentID,Exam1,Exam2,Exam3和Grade。我将studentID和成绩放入两个字符串数组中。
该程序只需要对studentID进行排序。但是,无论何时移动studentID,该studentID的等级也会被移动,因此在插入排序中具有成绩字符串。如果排序成功,程序应打印索引,studentID和成绩。
我成功地从文件中读取数据并将其打印出来,但是,我的插入排序似乎无法正常工作,因为在调用时没有打印出来:
//Declaration:
void insertionSort(char listID[],
char grades[],
int length);
//call
int main(void)
{
FILE* f = fopen("grades.csv", "r");
if (f == NULL) {
fprintf(stderr, "Error opening file test.dat.");
exit(1);
}
///////
char line[70];
int size = strlen(line);
char studentID[7];
char grade[2];
char exam1[3];
char exam2[3];
char exam3[3];
int num;
printf("\t+---------+-------+-------+-------+------+\n");
printf("\t| Student | Exam1 | Exam2 | Exam3 | Grade|\n");
printf("\t+---------+-------+------+-------+-------+\n");
while (fgets(line, sizeof(line), f) != NULL){
sscanf(line,
"%25[0123456789], %6[0123456789], %2[^,], %2[^,],%2[^,],%[ ABCD]",
studentID, exam1, exam2, exam3, grade);
printf("\t| %s | %+4s | %+4s | %+4s | %+4s \n ",
studentID, exam1, exam2, exam3, grade);
printf("\t+---------+-------+------+-------+------+\n");
for(int j=0; j<size; j++;)
{
insertionSort(studentID, grade, size-1);
printf( "\t %d | %s | %s\n", j, studentID, grade);
}
void insertionSort(char listID[], char grades[], int length)
{
int walk;
char key, key1;
bool located;
int current;
for (current = 1; current <= length; current++)
{
located = false;
key = listID[current];
key1= grades[current];
for (walk = current - 1; walk >= 0 && !located;)
{
if (key < listID[walk])
{
listID[walk+1] = listID[current];
grades[walk+1] = grades[current];
walk--;
}
else
located = true;
listID[walk+1] = key;
grades[walk+1] = key1;
}
}
}