0
我有一個分配從文件讀取類似表:讀從文件列插入結構
MERCURY VENUS EARTH MARS JUPITER SATURN URANUS NEPTUNE PLUTO
Mass(10^24kg) 0.33 4.87 5.97 0.642 1898 568 86.8 102 0.0146
Diameter(km) 4879 12104 12756 6792 142984 120536 51118 49528 2370
Density(kg/m^3) 5427 5243 5514 3933 1326 687 1271 1638 2095
Gravity(m/s^2) 3.7 8.9 9.8 3.7 23.1 9 8.7 11 0.7
Escape_Velocity(km/s) 4.3 10.4 11.2 5 59.5 35.5 21.3 23.5 1.3
Rotation_Period(hours) 1407.6 -5832.5 23.9 24.6 9.9 10.7 -17.2 16.1 -153.3
...
那裏有20類的值(質量,直徑,密度...) 和9顆行星。
我試圖將數據讀入struct planet
與20個組件(質量,直徑,密度等),它編譯,但我不能打印輸出中的任何結構組件(如p[2].A
),所以它看起來並不像我甚至從文件中讀取數據(我確實將它保存在正確的位置)。因爲我想讀列入struct
,這是一個有點亂......
typedef struct {char A[30]; char B[10]; char C[10]; float D; char E[10]; char F[10]; char G[10]; char H[10]; char I[10]; char J[10]; char K[10]; char L[10]; char M[10]; char N[10]; char O[10]; char P[10]; char Q[10]; char R[10]; char S[10]; char T[4]; char U[4];}planet;
int main(void) {
FILE * fp;
FILE * fs;
int i=0, j=0;
planet p[9];
char label[20][30];
char x[20][30];
fp=fopen("planets.txt", "r");
if (fp==NULL)printf("ERROR\n");
for(j=0; j<9; i++){ //this for loop read the planet names
fscanf(fp, "%s", p[i].A);
}
for(i=0; i<20; i++){ //this for loop counts the rows and reads the labels
fscanf(fp, "%s", label[i]); //label[0] corresponds to .B values
for(j=0; j<9; j++){ //this for loop reads values across the rows and assigns them to the labels
fscanf(fp, "%s", x[j]);
if (i==0)strcpy(p[j].B, x[j]);
else if (i==1) strcpy(p[j].C, x[j]);
else if (i==2){
p[j].D=atof(x[j]);
}
else if (i==3) strcpy(p[j].E, x[j]);
else if (i==4) strcpy(p[j].F, x[j]);
else if (i==5) strcpy(p[j].G, x[j]);
else if (i==6) strcpy(p[j].H, x[j]);
else if (i==7) strcpy(p[j].I, x[j]);
else if (i==8) strcpy(p[j].J, x[j]);
else if (i==9) strcpy(p[j].K, x[j]);
else if (i==10) strcpy(p[j].L, x[j]);
else if (i==11) strcpy(p[j].M, x[j]);
else if (i==12) strcpy(p[j].N, x[j]);
else if (i==13) strcpy(p[j].O, x[j]);
else if (i==14) strcpy(p[j].P, x[j]);
else if (i==15) strcpy(p[j].Q, x[j]);
else if (i==16) strcpy(p[j].R, x[j]);
else if (i==17) strcpy(p[j].S, x[j]);
else if (i==18) strcpy(p[j].T, x[j]);
else if (i==19) strcpy(p[j].U, x[j]);
}
i++;
}
...
任何人都可以看到這種方法有問題?
數據是否真的缺少第一行的標記'planet'或'name'?你的結構佈局是可惡的;白色空間很便宜,應該使用。結構元素的名稱是不透明的。目前尚不清楚爲什麼元素D是'float'時,其他所有元素都是'char'。你應該有一個'NUM_PLANETS'而不是9個(有趣的是冥王星已經恢復爲行星)。我不清楚你是如何跳過逗號的。你有沒有添加打印? –
對不起,這些逗號實際上並不在表格中,我只是將它鍵入來分隔事物。元素D(密度)是一個浮點數,因爲它是唯一被用作排序結構值的元素(我需要重新打印表格但行星按降密度排序)。其餘的元素無關緊要,所以我將它們作爲字符串讀取,以便我可以在新表格中重新打印它們。 我寫了一切排序和fprinft到另一個文件,我也試圖只是printf它直接退出,但沒有得到任何 – ari
是的,它缺少第一行的標籤 – ari