gpt4 book ai didi

c - 我已从 txt 文件读取数据并将其存储在结构体数组中,并希望按名称字段对数据进行排序

转载 作者:行者123 更新时间:2023-11-30 16:13:07 25 4
gpt4 key购买 nike

此代码不会给出任何错误,但会显示旧的数组值而不按名称字段排序,它会读取将数据存储在结构体数组 Student 中的 txt 文件,这是结构体 person 的实例,然后使用代码对其进行排序并打印排序后的数组的结果。但它不起作用

#include < stdio.h > 
#include < string.h >

int main() {
// read data from txt file and stores
// in a struct array

storeInarraySort();

}

int storeInarraySort() {

// struct person with 4 fields
struct person {
char name[100];
char address[100];
char IDnumber[20];
int age;
};


FILE * file = fopen("personout.txt", "r");

// declares an struct array to store data
struct person student[10];

int k = 0;

if (file != NULL)
{
char line[128]; /* or other suitable maximum line size */
/* read a line */
while (fgets(line, sizeof line, file) != NULL)
{

// stores values in struct array
sscanf(line, " %99[^,], %99[^,], %19[^,], %d", student[k].name,
student[k].address, student[k].IDnumber, & student[k].age);
k++;

}
printf("%d\n", k); // no of records in array

fclose(file);


// number of records k r=k first for loop
// inner for loop s=r+1
//char temp;
//struct person temp;

for (int r = 0; r < k - 1; r++) {
for (int s = r + 1; r < k; r++) {

if (strcmp(student[r].name, student[s].name) > 0) {

struct person temp = student[r];
//strcpy(temp,student[r]);
student[r] = student[s];
//strcpy(student[r],student[s]);
student[s] = temp;
//strcpy(student[s],temp);
}


}


}

// prints struct array to check
for (int t = 0; t < k; t++) {
printf("%s\n %s\n %s\n %d\n ", student[t].name,
student[t].address, student[t].IDnumber, student[t].age);
}

}


}

最佳答案

使用选择排序进行排序。

void swap(int *xp, int *yp)  
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)
{
int i, j, min_idx;

// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (strcmp(arr[j].name , arr[min_idx].name) < 0)
min_idx = j;

// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}

关于c - 我已从 txt 文件读取数据并将其存储在结构体数组中,并希望按名称字段对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58152867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com