[英]how To sort char name in a struct using C Language
如何在函數中對char firstName進行排序,並且已經從文本文件中讀取名稱,並且可以使用外部庫所有學生名稱都在文本文件中提供,該文件被讀入學生記錄數組中
struct student{
char*lastName; /*name of the student*/
char*firstName;
int age; /*age of the student*/
float grade[3];
}
qsort
函數通常在C中用於對數組進行排序。 其中一個參數是指向比較函數的指針。 編寫函數,以便以任何方式比較兩個指針。 您甚至可以使用不同的比較功能,以便在運行時選擇將應用的功能。
int StudentCompare(const void * elem1, const void * elem2)
{
const struct student * left = (const struct student *) elem1;
const struct student * right = (const struct student *) elem2;
int result;
result = strcmp(left.firstName, right.firstName);
if (result == 0)
result = strcmp(left.lastName, right.lastName);
return result;
}
假設您不允許使用外部庫,那么簡單的方法就是使用bubblesort。 編寫一個函數來確定struct student
的數組是否已經排序。 然后編寫一個遍歷這樣一個數組的函數,比較相鄰的學生對。 如果它們出現故障,請更換它們。 使用第一個函數的結果作為while循環的條件子句,將第二個函數作為正文。
如果你被允許使用它,那么stdlib.h
qsort()
是迄今為止最好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.