2015-10-15 44 views
-1

我想要做的是打開文件,讀取文件中的信息,向用戶詢問一系列數據,然後計算每個月的天數百分比範圍。該文件是一個包含一年中每個月每天的天氣數據(溫度)的文件。我很難用數組啓動程序,我不知道如何使用該數組從文件中獲取信息,然後計算並存儲我需要的信息。任何幫助表示讚賞,這是我到目前爲止的代碼:使用數組讀取文件

#include <stdio.h> 

int main() { 
    int range[12], total[12], i, cold, hot, sum, input, month, day, year; 
    float avg, temp; 
    char filename[20]; 

    printf("Tell me about your preferred temperature for flying:\n"); 
    printf("What is the coldest temperature you can fly in?\n"); 
    scanf("%d", &cold); 

    printf("What is the hottest temperature you can fly in?\n"); 
    scanf("%d", &hot); 

    FILE * ifp = 0; 
    printf("Please enter the name of the weather data file.\n"); 
    scanf("%s", filename); 
    ifp = fopen(filename, "r"); 

    return 0; 
} 

現在我剛剛已經開始完成,我認爲是正確的,但我不知道接下來該陣列做才能得到信息不在文本文件中。我不需要完成整個程序,我只需要幫助下一步該做什麼。這裏的輸出應該是什麼樣子的例子:

Tell me about your preferred temperature for flying: 
What is the coldest temperature you can fly in? 
60 

What is the hottest temperature you can fly in? 
80 

Please enter the name of the weather data file. 
weather.txt 

Month 1: 59.2 percent of days in range. 
Month 2: 69.2 percent of days in range. 
Month 3: 72.6 percent of days in range. 
Month 4: 92.6 percent of days in range. 
Month 5: 98.7 percent of days in range. 
Month 6: 48.3 percent of days in range. 
Month 7: 36.41 percent of days in range. 
Month 8: 18.9 percent of days in range. 
Month 9: 57.64 percent of days in range. 
Month 10: 100.00 percent of days in range. 
Month 11: 65.4 percent of days in range. 
Month 12: 80.5 percent of days in range. 

I recommend month 10 for the flight! 

編輯: 文本文件的格式如下:

1    1    2013   63.4 
1    2    2013   66.1 
1    3    2013   67.2 
+0

首先學習你應該閱讀的文件格式,然後從文件中考慮你需要的數據。最後想想你需要真正閱讀這些數據的函數,你應該使用'fscanf','fgets'還是其他的? –

+0

分配轉儲。根本沒有實際的核心工作。什麼代碼非常類似http://stackoverflow.com/questions/33144059/using-arrays-to-read-a-file-and-get-information –

+0

我投票結束這個問題作爲題外話,因爲家庭作業垃圾郵件。 –

回答

1

使用fgets

The available data is presented in four columns per day: 
MONTH   DAY   YEAR   TEMPERATURE 
The file will end with a -1 on a row by itself. 

從文件實例打開後從文件中讀取 -

char data[100]; 
while(fgets(data,sizeof data,ifp)!=NULL){ 
    // get temperature out of array 
    // convert it and store in a variable 
} 

或者如果文件中的數據是固定格式,請使用fscanf

注意 - 檢查returnfopen