我想讀取下面的資料并將其存盤在一個結構中并按最舊的排序。我想將一個帶有排序資料的結構寫入一個新檔案。(按從大到小升序排列)
資料:
24 Zachary Gordon
54 Cuba Gooding
67 Peter Killian Gallagher
36 Kyle Gallner
我想要的輸出:
24 Zachary Gordon
36 Kyle Gallner
54 Cuba Gooding
67 Peter Killian Gallagher
我的代碼:
#include <stdio.h>
#define N 4
struct Data {
int age;
char name[30];
};
void sortData(struct Data aa[]);
int main() {
struct Data aa[N];
struct Data tmp;
FILE *input, *output;
input = fopen("data.txt", "r");
output = fopen("output.txt", "w");
if (input == NULL) {
printf("Fail to read file");
}
for (int i = 0; i < N; i ) {
fscanf(input, "%d", &aa[i].name);
fgets(aa[i].name, 30, input);
}
for (int i = 0; i < N; i ) {
printf("%d %s", aa[i].age, aa[i].name);
}
fclose(input);
sortData(aa);
for (int i = 0; i < N; i ) {
fprintf(output, "%d %s", aa[i].age, aa[i].name);
}
return 0;
}
void sortData(struct Data aa[]) {
struct Data tmp;
for (int i = 0; i < N - 1; i ) {
for (int j = i 1; j < N; j ) {
if (aa[i].age > aa[j].age) {
tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
}
}
我不知道出了什么問題。提前感謝那些會回復的人
uj5u.com熱心網友回復:
在嘗試您的代碼時,我收到了一些關于從 data.txt 檔案中掃描資料的警告,并且也沒有看到代碼實際存盤年齡的位置。考慮到這一點,我對代碼進行了一些調整,如下所示:
#include <stdio.h>
#define N 4
struct Data {
int age;
char name[30];
};
void sortData(struct Data aa[]);
int main() {
struct Data aa[N];
//struct Data tmp; /* Don't need this here. It is defined within the function as a local structure */
char data[65];
FILE *input, *output;
input = fopen("data.txt", "r");
output = fopen("output.txt", "w");
if (input == NULL) {
printf("Fail to read file");
}
for (int i = 0; i < N; i ) {
fgets(data, 64, input); /* Read in the full line first */
sscanf(data, "%d %[^\n]", &aa[i].age, aa[i].name); /* Then parse it to separate and store the age and name */
}
for (int i = 0; i < N; i ) {
printf("%d %s\n", aa[i].age, aa[i].name);
}
fclose(input);
sortData(aa);
for (int i = 0; i < N; i ) {
fprintf(output, "%d %s\n", aa[i].age, aa[i].name);
}
return 0;
}
void sortData(struct Data aa[]) {
struct Data tmp;
for (int i = 0; i < N - 1; i ) {
for (int j = i 1; j < N; j ) {
if (aa[i].age > aa[j].age) {
tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
}
}
需要指出的一些專案。
- 不是使用 fscanf 從檔案中讀取一行資料,而是使用 fgets 函式來獲取完整的資料行。
- 輸入整行資料后,呼叫sscanf函式決議行并將年齡存盤到結構的年齡元素中,然后將名稱存盤到結構的名稱元素中。
通過這些調整并使用您的資料創建一個文本檔案,可以在終端查看以下資料。
@Dev:~/C_Programs/Console/StructureSort/bin/Release$ ./StructureSort
24 Zachary Gordon
54 Cuba Gooding
67 Peter Killian Gallagher
36 Kyle Gallner
試一試,看看它是否符合您專案的精神。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/532993.html
標籤:C文件排序结构
